简体   繁体   English

如何获取JavaScript以在Bootstrap弹出窗口中执行?

[英]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. 元素是由bootstrap的popover组件动态创建的,您不能事先为其分配侦听器。

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. 那是事件委托。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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