This article mainly introduces the solution to the problem that jQuery dynamically added elements cannot trigger binding events. It analyzes the reasons why dynamically added elements cannot bind events and related solutions in the form of examples. Friends in need can refer to the following
The example in this article describes the solution to the problem that jQuery dynamically added elements cannot trigger binding events. Share it with everyone for your reference, the details are as follows:
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('这里是动态元素添加的事件'); }
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to use jQuery CSS Implement table table
Use http module to send requests through nodejs (detailed tutorial)
How to use Angular to implement internationalization (detailed tutorial)
The above is the detailed content of How to solve the problem that dynamically added elements cannot trigger binding events using jQuery. For more information, please follow other related articles on the PHP Chinese website!