jQuery binding the click event of a dynamic element has no effect

I have been plagued by this problem before. When I wrote ajax to load data, I found that the demo node element added later lost the previous click event. Why does the click event fail, and how can we solve it? Well, let's briefly explain it through the following example.

An example is as follows:

<div>
  <ul id="demo"> <li>Kubernetes:下一代分布式系统的护戒使者</li> <li>机器学习工具--Pandas cheat sheet</li> <li>Android 8.0 正式版即将发布 谷歌还要建超人模型</li> ... //li是动态生成 </ul> </div> <script type="text/javascript"> //动态像ul的末尾追加一个新元素 $("#demo").append('<li>Kubernetes:下一代分布式系统的护戒使者</li>'); $("#demo").append('机器学习工具--Pandas cheat sheet'); $("#demo").append('Android 8.0 正式版即将发布 谷歌还要建超人模型'); ... </script>

Error example:

// 示范一
$("#demo li").click(function(){ alert($(this).html()); }); // 示范二 $("#demo li").on('click',function(){ alert($(this).html()); });

By running the above code, you will find that the click event bound to the dynamically generated label in advance does not respond when clicked. To sum up, it is speculated that the above listener function specifies the object when the web page is loaded, and the element appended by code, such as the element appended by js, cannot match this event. So, what should we use to bind dynamic elements? Live and on are supported to bind events to dynamic elements and attributes. Live is deprecated after JQUERY 1.7. Now mainly use on, when using on, also pay attention, the elements in front of on must also exist in the dom when the page is loaded. Dynamic elements or styles, etc., can be placed in the second parameter of on.

Correct example:

$("#demo").on('click', 'li',function(){ alert($(this).html()); });

The above is the relevant knowledge of the jQuery on() method that Xiaobian introduced to you to bind the click event of dynamic elements, and I hope it will be helpful to you.

Guess you like

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