Home  >  Article  >  Web Front-end  >  How to solve the problem that jQuery ajax dynamically new nodes cannot trigger click events

How to solve the problem that jQuery ajax dynamically new nodes cannot trigger click events

小云云
小云云Original
2018-01-10 13:43:021962browse

When writing ajax to load data, I found that the demo node element added later lost the previous click event. How to solve this problem? The editor below brings you a solution to the problem that jQuery ajax dynamically added nodes cannot trigger click events. Let's take a look. I hope it can help you.

When writing ajax to load data, I found that the demo node element added later lost the previous click event. Why does the click event fail? How should we solve it?

In fact, the simplest way is to write onclick="" directly in the tag, but writing this way is actually a bit low. The best way is to give The class name binds a click event.

Two solutions to the problem that jQuery ajax dynamically added nodes cannot trigger events. In order to achieve a better demonstration effect, assume that there is code with the following structure under the body of a page:

 
      
  • a1
  •   
  • a2
  •   
  • a3
  •  
   

Method 1: Use live:

The live() function will bind one or more event handlers to the selected element and specify the functions to be run when these events occur. The live() function is applied to the current and future elements matching the selector. For example, elements created dynamically through scripts.

The implementation is as follows:

$('.demo1').live('click', function(){
 alert('OK');
});

Method 2: Use on:

You can bind events through the on method, which can be bound to its parent or body, the implementation is as follows :

$("#demo").on('click','.demol',function(){
 alert('OK')
});

Through the above two methods, you can solve the problem of jQuery ajax dynamically adding nodes that cannot trigger click events. Now that you know the method, try it quickly.

Related recommendations:

JQuery simulates click events and automatically triggers events

js simulates click events

Detailed explanation of common errors in js dynamically adding click events

The above is the detailed content of How to solve the problem that jQuery ajax dynamically new nodes cannot trigger click events. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn