Case Study of jQuery Implementation Adding Event Method to Newly Added Elements

  • 2021-07-18 06:59:35
  • OfStack

This article illustrates the jQuery implementation of adding event methods to newly added elements. Share it for your reference, as follows:

Recently, the project team needed to add time to the new elements. Some people said that when the live method was used later, it was found that jQuery did not have this method (1.7 or more did not) and replaced it with on

In addition to the official example of jquery api, there are the following examples to add events to new elements


$(document).on("click",'#lyysb a',function(){
  if(!$(this).hasClass('cur')){
    $(this).addClass('cur');
  } else {
    $(this).removeClass('cur');
  }
});

But binding events to docunmet is no different from the original live method. In the original live () method, the handler function is bound to document object by default. If DOM nested structure is deep, event bubbling through a large number of ancestor elements will lead to great performance loss. With the. on () method, events are only bound to elements that match the selector expression of the $() function, so you can pinpoint the 1 part of the page and reduce the overhead of event bubbling.


<div id="zkdiv">
  <input type="button" value=" Unfold " id="zk" class="zk"/> <br>
</div>

For example, I will dynamically add several dom nodes with class= "zk" in zkdiv, and if I want to bind the same event to the dynamically added nodes, I can do it through the following code


// Expand button clicks to trigger events 
$("#zkdiv").on("click",".zk",function(){
  console.log("on  Click 1 Times ");
});
var html2 = "<input type='button' class='zk' value=' Newly generated expansion ' />";
$("#zkdiv").append(html2);

Thus, the 1 handler is bound to the selector of # zkdiv, and the performance loss caused by event bubbling is greatly reduced. (When using this method, make sure that the selector before. on can select an object or it will not work.)

For more readers interested in jQuery related content, please check the topics of this site: "Summary of Usage and Skills of Common Events of jQuery", "Summary of Common Plug-ins and Usage of jQuery", "Summary of Data Skills of json Operation of jQuery", "Summary of Extension Skills of jQuery", "Summary of Drag and Drop Effects and Skills of jQuery", "Summary of Operation Skills of jQuery Table (table)", "Summary of Common Classic Special Effects of jQuery", "Summary of Animation and Special Effects Usage of jQuery" and "Usage of jquery Selector"

I hope this article is helpful to everyone's jQuery programming.


Related articles: