简体   繁体   中英

Bind event on element that's not in dom

I have a script that adds a <tr> dynamically, outside it seems that the elements contained in it are not recognized by jQuery because it is not yet loaded into the DOM.

I try to use .on function , but it is not working.

Have you an idea ?

$(document).ready(function(){
  $("#add_item").click(function(e){
    e.preventDefault();
    var nbeTr = $(".tablerow").length;
    if (nbeTr < 10){
      $(".tablerow:last").after("<tr class='filleul'><td></td><td></td><td></td><td><button class='newtr'>X</button></td></tr>");
    }
  });
  $(document).on("click", ".newtr", function(event) {
    event.preventDefault();
    alert("Yo");
  });
});

You'll need to register the event listener when creating the button element. Right now you're trying to register click events to undefined elements.

// create button
$ele = $("<button class='newtr'>X</button>");
// bind event listener to button
$ele.on("click", function() { alert("hello"); });
// insert $ele into DOM
$target.append($ele);

Hey Buck your code is working, I think problem is some where else.

See this working example:

 $(document).ready(function() { $("#add_item").click(function(e) { e.preventDefault(); var nbeTr = $(".tablerow").length; if (nbeTr < 10) { $(".tablerow:last").after("<tr class='tablerow filleul'><td>1</td><td>2</td><td>3</td><td><button class='newtr'>X</button></td></tr>"); } }); $(document).on("click", ".newtr", function(event) { event.preventDefault(); alert("Yo"); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <button id='add_item'>Add item</button> <table> <tr class='tablerow'> <td>c1</td> <td>c2</td> <td>c3</td> <td> <button class='newtr'>X</button> </td> </tr> <table> 

Ok, the problem was a bad version of jQuery was using.

I just use CDN of last jQuery version and refresh cache and it's working.

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