[英]After making an AJAX call my jQuery function dies
HTML:
<div class="divses">
<div class="point" data-id3="'.$id3.'" data-values2="'.$values2.'">
<input type="button" class="buttonic"></input>
<input type="button" class="buttonic"></input>
<input type="button" class="flag"></input>
</div>
</div>
jQuery的:
$(".flag").click(function() {
var id3 = alert($(this).parent().data("id3"));
})
我的HTML和JavaScript就是這樣,當我單擊標志按鈕時,它會警告data-id3(效果很好)。 我的問題在撥打AJAX電話后開始
AJAX:
var page = $(".buttonic").data("page");
var XHR = new XMLHttpRequest();
XHR.open("POST", "turnthepage.php", true);
XHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
XHR.onreadystatechange = function() {
if(XHR.readyState == 4 && XHR.status == 200) {
$(".divses").children(".point").remove();
$(".divses").append(XHR.responseText);
}
}
XHR.send("page="+page);
XHR.responseText等於此HTML代碼
<div class="point" data-id3="'.$id3.'" data-values2="'.$values2.'">
<input type="button" class="buttonic" />
<input type="button" class="buttonic" />
<input type="button" class="flag" />
</div>
看起來我正在獲取相同的HTML,但是我的$ id3和$ values2變量發生了變化,這就是為什么我進行AJAX調用。
得到這個之后,我的新HTML:
<div class="divses">
<div class="point" data-id3="'.$id3.'" data-values2="'.$values2.'">
<input type="button" class="buttonic"></input>
<input type="button" class="buttonic"></input>
<input type="button" class="flag"></input>
</div>
</div><!-- please pay attention it is not same as first HTML $id3 and $values2 has changed. -->
在那部分之后,我單擊新的.flag
按鈕,但是什么也沒有發生。 為什么我的jQuery部分在進行AJAX調用后變得無用。我的所有站點都相同,我的jQuery也一樣,但是當我單擊新的.flag
按鈕時,jQuery不起作用。
可能是什么問題呢?
DOM正在通過AJAX進行修改,從而影響了事件監聽器。 將$(".flag").click()
函數移至if語句內XHR.onreadystatechange函數的底部,或使用以下命令:
$(document).on('click', '.flag', function () {
var id3 = alert($(this).parent().data("id3"));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.