Home  >  Article  >  Web Front-end  >  How to add events to non-existent elements in jquery

How to add events to non-existent elements in jquery

coldplay.xixi
coldplay.xixiOriginal
2020-12-25 09:56:152600browse

Jquery method of adding events to non-existent elements: 1. Before [jquery1.9] version, use the live method, the code is [$("#id").live("click", function ( )]; 2. After the [jquery1.9] version, use the On method.

How to add events to non-existent elements in jquery

The operating environment of this tutorial: windows7 system, jquery3.2.1&&jquery1.9 version , DELL G3 computer.

Recommended: jquery video tutorial

jquery to add non-existent elements Event method:

Question:

It is very simple to add events to elements in jquery, such as adding a click event.

$(选择器).click(function(){ 
  );

However, ajax paging is done in the project, and the first page is loaded directly. Using the above method, there is no problem at all. However, when using ajax paging, the content of other pages is added later through innerHTML, and the added elements There are no related events.

In fact, the reason is also easy to understand. When the event was first added, the elements of other pages did not exist. After adding it later through innerHTML, the tags did exist, but the corresponding There are no events.

So, how to solve the above summary? Add events to non-existent elements

Solution:

Use the live method: Bind events to non-existent elements

$("#id").live("click", function () { 
            alert("ok"); 
     });

However, after jquery version 1.9, the live method was deleted. So what method should be used to replace live?

Answer , that is, using the on method

$("#id").on("click",function(){ 
           alert("ok"); 
   });

However, after using the on method, it is found that it is still invalid. There is no problem with the syntax, so why does it not work? The answer is that it should not be written like this. If it is to add an event to an element that does not exist,

To use the following writing method:

$(document).on("click",'#id', 
     function(){ 
        alert("ok"); 
    });

Use the above writing method, the problem will be solved.

Related free learning recommendations: javascript(Video)

The above is the detailed content of How to add events to non-existent elements in jquery. 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