简体   繁体   中英

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"));
})

My HTML and JavaScript is just like that and when I clicked flag button it alerts data-id3(works great). My problem start after making an AJAX call

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

<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.

after getting this, my new 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. 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.

What could be the problem?

The DOM is being modified via AJAX, affecting your event listener. Move your $(".flag").click() function to the bottom of your XHR.onreadystatechange function inside the if statement, or use the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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