This article is a mirror article of machine translation, please click here to jump to the original article.

View: 15235|Reply: 1

[Jquery] There are two ways to solve the problem that dynamically added element nodes in jquery cannot trigger events

[Copy link]
Posted on 6/28/2016 12:43:24 PM | | |
For example, when making an ajax to read the message list, there is a reply button after each message, the class is "reply", if you use $(".reply").click(function(){ //do something... }), presumably the reply button in the list loaded by ajax later, the click event will be invalid.
In fact, the easiest way is to write onclick="" directly in the tag, but writing this is actually a bit low, and the best way is to bind a click event to the class name.
There are two ways to solve the problem that dynamically added element nodes in jquery cannot trigger events, as follows:
For better presentation, let's say you have code with the following structure under the body of a certain page:


Method 1: Use live
The live() function binds one or more event handlers to the selected element and specifies which functions to run when those events occur. The live() function applies to matching the current and future elements of the selector. For example, elements created dynamically through scripts.
The implementation is as follows:


Method 2: Use on
You can bind an event to its parent or body through the on method, as follows:


Now you can try to see if the problem has been solved, I hope this article can really help you.

The second one I use is to bind the parent level element...





Previous:js Json objects are interchanged with Json strings
Next:js number is passed into the method, and the value is added by one or minus one
Posted on 7/8/2016 2:34:49 PM |
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com