简体   繁体   中英

How can I get JavaScript to execute inside a Bootstrap popover?

I have a popover for each link to a user containing their avatar and option to follow/unfollow. The follow/unfollow functionality works but not in a popover?

$('body').popover({ selector: '[data-popover]', trigger: 'click hover', placement: 'top', delay: {show: 50, hide: 400}});

$('.follow-user .follow, .follow-user .unfollow').on('click', function(){
    var el = $(this);

    var actionType = el.hasClass('unfollow') ? 'unfollow' : 'follow';

    var data = {
        actionType: actionType,
        userId: el.attr("data-uid")
    };

    $.ajax({
        type: 'POST',
        url: '{{path('ajax_follow_user')}}',
        data: data,
        dataType: 'json',
        error: function(){
            alert('Error. please try again later!');
            el.removeClass('following');
        },
        beforeSend: function(){
            el.addClass('following');
        },
        success: function(r){
            alert("success");
            if(r.error != '') {
                alert(r.error);
                return false;
            }
            alert(actionType);
            if (actionType == 'follow')
            {
                el.text("Unfollow");
                el.stop().removeClass('follow').addClass('unfollow');
            }
            else if (actionType == 'unfollow')
            {
                el.text("Follow");
                el.stop().removeClass('unfollow').addClass('follow');
            }

            el.removeClass('following').text(r.label);
        }
    });
});

.

<a href="#"
       data-popover="true"
       data-html="true"
       data-content='
<img src="{{ asset(user.avatar) }}" alt="{{ user.username }}"
     width="80" height="80" style="float:left; margin: 0 10px 10px 0"/> 
<strong>{{ user.username }}</strong> <br />
<span class="follow-user"><a class="follow" data-uid="{{ user.id }}">Follow</a></span> 
<div style="clear:both"></div> <br />'>
        {{ user.username }}
    </a>

The elements are created dinamically by the popover component of bootstrap, and you cannot assign listeners to them beforehand.

However, event bubbling lets you attach the listener to the parent element (or its parent, up to the document) in the form

$(document).on('click', '.follow-user .follow, .follow-user .unfollow', function(){
    var el = $(this);
    ...
});

that's event delegation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM