Home > Article > Web Front-end > How to deal with jQuery failing to trigger binding events when adding elements
This time I will bring you jQuery's failure to trigger binding when adding elements EventsHow to deal with jQuery's failure to trigger binding events when adding elementsWhat are the precautions , the following is a practical case, let’s take a look.
I recently encountered a problem, that is, after using jquery to dynamically add elements, I found that the dynamically added elements could not trigger events. Later, I checked some information on the Internet and found that it was supposed to be handled like this:
First, let’s talk about my error code:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="external nofollow" > <script src="//cdn.bootcss.com/jquery/1.8.3/jquery.min.js"></script> <script> $(document).ready(function(){ //这里是动态添加元素 $(".add").click(function(){ var btn = $("<button class='newBtn btn btn-default'>新按钮</button>"); $("body").append(btn); })<br><br>//这里是为添加的元素添加事件 $(".newBtn").click(function(){ alert("这里是新添加的元素触发的事件"); }) }) </script> </head> <body> <button class=" add btn btn-default">添加按钮</button> </body> </html>
Here’s my solution
Method 1: Bind live events (live events are only supported below jquery 1.9, not higher versions).
$(".newBtn").live("click",function(){ ///jquery 1.9(不包括1.9)以下可以 alert('这里是动态元素添加的事件'); })
Method 2: Use on() event binding($(ParentEle).on("click",".thisEle",function(){ })
$("body").on("click", ".newBtn", function() { alert('这里是动态元素添加的事件'); }); //这里的ParentEle是 thisEle的父辈元素或者祖先元素,ParentEle可以是document,也可以是body等。 //注意:如果此时调用的函数是外部定义好的函数,那在调用的时候不要加(),不然会跳过点击事件直接触发函数
$("body").on("click", ".newBtn",aa ); function aa(){ alert('这里是动态元素添加的事件'); }
ok, the problem is solved, continue to climb the pit
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
What should be done if the jquery trigger function cannot trigger a tag
How to use jquer to implement table rows and columns Interchange
jquery's form validation submit
jQuery's checkbox selection and get the value
The above is the detailed content of How to deal with jQuery failing to trigger binding events when adding elements. For more information, please follow other related articles on the PHP Chinese website!