Javascript 通过ajax重新加载页面内容时,jQuery不起作用
我使用Bootstrap来显示一个popover,直到所有这些代码都正常工作Javascript 通过ajax重新加载页面内容时,jQuery不起作用,javascript,php,html,twitter-bootstrap,twitter-bootstrap-3,Javascript,Php,Html,Twitter Bootstrap,Twitter Bootstrap 3,我使用Bootstrap来显示一个popover,直到所有这些代码都正常工作 $(".emoticons").popover({ html : true, placement : 'bottom', animation : true, delay: { show: 100, hide: 500 }, content: function() {return $('.emoticonimg').html(); } }); 我只需要通过ajax加载页
$(".emoticons").popover({
html : true,
placement : 'bottom',
animation : true,
delay: { show: 100, hide: 500 },
content: function() {return $('.emoticonimg').html();
}
});
我只需要通过ajax加载页面的内容,然后我更改了代码,因为当我动态加载内容时,我需要委派事件,更改了代码,结果如下所示:
$('body').on('click','.emoticons',function()
{
$(".emoticons").popover({
html : true,
placement : 'bottom',
animation : true,
delay: { show: 100, hide: 500 },
content: function() {return $('.emoticonimg').html();
}
});
});
现在我的麻烦开始了。但是,当我第一次单击该代码时,它会工作,因此当我在链接上单击多次时,它会工作。怎么办?它第一次不起作用,因为第一次单击if会触发绑定popover的body onclick处理程序 在$(document).ready()函数中尝试类似的操作
$(".emoticons").click(function(){
$(this).popover({
html : true,
placement : 'bottom',
animation : true,
delay: { show: 100, hide: 500 },
content: function() {return $('.emoticonimg').html();
}
});
});
发生的情况是,当您单击
.emotics
并执行popover
功能时,您正在将其绑定到您的单击。这就是为什么它第一次不起作用,但后来起作用了。在此之后,它开始侦听单击事件
理想情况下,解决方案是在加载新内容时(在AJAX回调上)运行.popover
函数
如果只想复制粘贴我的代码并查看其是否有效,可以执行以下操作:
$('body').on('click','.emoticons',function()
{
// Convert this element into a popover and then display it
$(this).popover({
html : true,
placement : 'bottom',
animation : true,
delay: { show: 100, hide: 500 },
content: function() {
return $('.emoticonimg').html();
}
}).popover('toggle');
});
但是,我并不特别推荐这段代码,因为每次单击popover时都会重新初始化它
如果在AJAX请求完成后绑定所有弹出窗口,则会更好、更清晰:
$.ajax( "BlaBlaBla.php" )
.done(function() {
// Convert all emoticons to popovers
$(".emoticons").popover({
html : true,
placement : 'bottom',
animation : true,
delay: { show: 100, hide: 500 },
content: function() {
return $('.emoticonimg').html();
}
});
});
不起作用…只在我做第二次点击时起作用我说试试这样做-没有人会为你编写代码。这不起作用,因为它只在加载DOM时绑定,而在添加新内容时在ajax调用后绑定。因此,将其插入ajax回调中,以便适当地绑定。这不是一个非常优雅的解决方案,但你可以可以将它放在函数中,并在ajax函数的回调中调用它。如果页面上已经有.emotics
,您可能必须首先解除绑定…他说的没错,问题是它只在我第一次单击时起作用,而不是第二次单击后显示弹出框