简体   繁体   English

进行AJAX调用后,我的jQuery函数死亡

[英]After making an AJAX call my jQuery function dies

HTML: 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: jQuery的:

$(".flag").click(function() {
  var id3 = alert($(this).parent().data("id3"));
})

My HTML and JavaScript is just like that and when I clicked flag button it alerts data-id3(works great). 我的HTML和JavaScript就是这样,当我单击标志按钮时,它会警告data-id3(效果很好)。 My problem start after making an AJAX call 我的问题在拨打AJAX电话后开始

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 is equal this HTML code 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>

It looks like I'm getting same HTML but my $id3 and $values2 variables chancing and that's why I make an AJAX call. 看起来我正在获取相同的HTML,但是我的$ id3和$ values2变量发生了变化,这就是为什么我进行AJAX调用。

after getting this, my new HTML: 得到这个之后,我的新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. -->

After that part I click my new .flag button but nothing happens. 在那部分之后,我单击新的.flag按钮,但是什么也没有发生。 Why my jQuery section become useless after making an AJAX call.my all site is same and my jQuery is same but when I click my new .flag button jQuery doesn't work. 为什么我的jQuery部分在进行AJAX调用后变得无用。我的所有站点都相同,我的jQuery也一样,但是当我单击新的.flag按钮时,jQuery不起作用。

What could be the problem? 可能是什么问题呢?

The DOM is being modified via AJAX, affecting your event listener. DOM正在通过AJAX进行修改,从而影响了事件监听器。 Move your $(".flag").click() function to the bottom of your XHR.onreadystatechange function inside the if statement, or use the following: $(".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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM