[英]jQuery fails on DOM element inserted by AJAX
我在名為close
類上編寫了一個簡單的jQuery函數。
$(function () {
$(".close").click(function () {
$(this).parent().fadeTo(400, 0, function () { // Links with the class "close" will close parent
$(this).slideUp(400);
});
return false;
});
});
它運作良好,但是如果我使用AJAX插入新的DOM元素,此功能將失敗嗎? 為什么會這樣呢? 雖然我知道在通過AJAX響應插入的頁面上編寫相同功能的解決方案。 我做到了,它正在工作。 為什么它在全球不起作用?
我試圖將$(".close").click(function () {
替換$(".close").on("click", function(event){
但是它沒有給我確切的解決方案問題。
因為單擊事件起作用,所以元素應該出現在文檔中... on
委托事件上使用
$(document).on("click",".close",function () {
$(this).parent().fadeTo(400, 0, function () { // Links with the class "close" will close parent
$(this).slideUp(400);
});
return false;
});
在ajax成功函數起作用后添加您的click事件,但是我更喜歡使用on
委托事件(因為為此目的引入了jquery中的on
)。
我建議您使用最接近的靜態父級,而不是document
本身,以提高性能。
鏈接以了解有關事件事件的更多信息
因為當DOM准備就緒時,jQuery將click
事件綁定到了元素。 它不會監視與選擇器匹配的新元素,因此之后添加的任何元素都不會將click事件綁定到您的函數。 為此,您必須在AJAX請求完成后執行$('.close').click(...)
。
您是否嘗試過使用“實時”方法。
$(".close").live('click',function () {
$(this).parent().fadeTo(400, 0, function () { // Links with the class "close" will close parent
$(this).slideUp(400);
});
return false;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.