$('[data-toggle= "popover" ]') 不选择任何内容



我有一个页面,div的内容由.post请求填充,项目:<div data-toggle="popover" ....><a><img></a></div>,这部分工作正常。但是当我之后尝试通过选择[data toggle="popover"]jquery return"[]"来激活popover时,有什么想法吗?(切割代码只是为了显示主要思想)。

<script>
    function updateGallery() {
        $.post('/images/?action=list', '', function (data) {
            for (var item in data.result) {
                gallery_dom += '
<div data-toggle="popover" data-placement="bottom" title="'+ item.size +'">'+
'<a class="thumbnail">'+
'<img id="gal-' + item.id + '" class="image" big="'+item._big+'" src="' + item._src + '"></a></div>';
                } // for
$('#gallery-list').empty();
$('#gallery-list').html(gallery_dom);
}
}
</script>
<div id="gallery-list"></div>

<script>
$(function(){
updateGallery();
console.log($('[data-toggle="popover"]));
</script>

您需要在ajax success回调中激活popover。这时您可以确定新内容已经添加到DOM中。也许就在$('#gallery-list').html(gallery_dom);之后,在updateGallery()函数中。

试着把console.log($('[data-toggle="popover"]);放在那行后面。

如果您想测试Gallery是否已正确更新,您可以使用一个临时HTML元素(div、按钮等)并在其上附加一个事件处理程序

<div id="gallery-list"></div>
<div id="testGallery">Click here to test Gallery</div>

并使用此JS允许控制台正确记录结果(一旦您看到Gallery已经更新)。

$('#testGallery').click(function(){
            console.log($('[data-toggle="popover"]'));    
});

或者,您可以使用全局标志(不是我最喜欢的工具,但它有效)或其他机制让您的代码知道Gallery已经更新。在发送AJAX请求之前,您将标志设置为"not updated",当它完成时("done"回调),您将其设置回"updated"。

要做到这一点,您需要传递一个函数作为参数


1°步骤: 您希望在$.post()之后执行什么函数

function afterPost() {
    console.log( $('[data-toggle="popover"]') );
}

2°步骤:在函数中引用它作为参数,并在$.post()之后调用它:

function updateGallery( callback ) {
    $.post('/images/?action=list', '', function (data) {
         /*
             ...
         */
         callback();
    }
}

3°步,最后:使用它

$(function(){
    updateGallery( afterPost );
})

**希望有帮助!**

最新更新