[英]jQuery does not work when reload the page content via ajax
我使用Bootstrap顯示彈出窗口,直到所有下面的代碼都正常為止。
$(".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();
}
});
});
現在我的煩惱開始了。 但是,當我第一次單擊該代碼時,它不起作用,因此,當我多次單擊鏈接時,該代碼就起作用了。 該怎么辦?
第一次無法使用,是因為第一次觸發(如果觸發了綁定了您的彈出框的正文onclick處理程序)。
在$(document).ready()函數中嘗試類似的操作。
$(".emoticons").click(function(){
$(this).popover({
html : true,
placement : 'bottom',
animation : true,
delay: { show: 100, hide: 500 },
content: function() {return $('.emoticonimg').html();
}
});
});
發生的事情是,當您單擊.emoticons
並執行您的popover
功能時,就是在此時將其綁定到您的點擊上。 這就是為什么它第一次不起作用,但后來卻起作用的原因。 之后,它開始監聽click
事件。
理想情況下,解決方案是在加載新內容時(在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');
});
但是,我不會特別推薦此代碼,因為每次單擊彈出窗口時都會重新初始化它。
在完成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();
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.