如何在Bootstrap popover中执行JavaScript?

时间:2014-07-04 20:16:46

标签: javascript php html twitter-bootstrap-3

我有一个包含其头像的用户的每个链接的弹出窗口以及关注/取消关注的选项。跟随/取消关注功能是否有效但不是在弹出框中?

$('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>

1 个答案:

答案 0 :(得分:1)

元素是由bootstrap的popover组件以dinamically方式创建的,你不能事先为它们分配监听器。

但是,事件冒泡允许您将侦听器附加到父元素(或其父元素,直到文档),格式为

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

那是事件委托。