Solution for event handling not working after adding elements dynamically for js.

Code that doesn't work:

例子:$(".baby").on("click",function(){

 $(this).parent().parent().parent().append("<tr><td><input class='baby'  type='text'></td><td><input  class='reel' type='text'></td><td><input class='ifxreel'  type='text'></td><td><input class='ifxbox' type='text'></td></tr>") ;            

  })

The new element added by the above code, the element with class="baby", does not realize the click function we want after clicking.

solution:

$('body').on("click",'.baby',function(){
    $(this).parent().parent().parent().append("<tr><td><input class='baby'  type='text'></td><td><input  class='reel' type='text'></td><td><input class='ifxreel'  type='text'></td><td><input class='ifxbox' type='text'></td></tr>") ;  

})

The revised code completely solves the previous trouble. Of course, you can also encapsulate the click event into a function method, and then call this method after adding the element. It's just that the amount of code will be doubled. So using the above method, I think it is the best.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325064731&siteId=291194637
Recommended