Home > Web Front-end > JS Tutorial > body text

How to add events to non-existent elements in jquery

coldplay.xixi
Release: 2023-01-04 09:38:06
Original
2603 people have browsed it

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(){ 
  );
Copy after login

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"); 
     });
Copy after login

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"); 
   });
Copy after login

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"); 
    });
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template