How to bind events to dynamically generated tags in jquery

php中世界最好的语言
Release: 2018-03-14 16:31:50
Original
1659 people have browsed it

This time I will bring youjqueryHow to bind dynamically generated tagsEvents, jqueryNotes on binding events to dynamically generated tagsWhat are they? Here are actual cases. Let’s take a look.

I often encounter the difficulty of binding events to dynamically generated tags. I briefly tested and summarized it. The conclusion is as follows:

  

生成a标签

Copy after login

Click the button and a li will be added to d2. Label, this is OK.

However, if this is done during initialization, it is invalid to use the bind method to bind the li tag that will be dynamically generated in the future. Clicking the generated li tag will not cause any reaction.

Because the bind method can only bind events to the static label jq object that already exists when it is executed, it is invalid for future dynamically added labels.

At this time, there are several ways to solve this problem:

Method 1:

  

动态生成a标签

Copy after login

This method It is to splice the native js events to be triggered during dynamic splicing, and then define the event method in the script tag. This method can trigger the click event of li. But if you want to use alert($(this).text()), which prints the label's own information, no results will be displayed. Even if the label is printed statically, it will not be displayed.

To solve this problem, you can use the following two methods.

Method 2:

  

生成a标签

Copy after login

This method can solve the above problem. Although it also uses the bind method, please note that it first has the target tag object and then calls the bind method, so it is easy to use. And it can actually print its own information normally, which is amazing.

Method three:

  

测试静态标签的绑定方法


动态生成a标签的位置

Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website !

Recommended reading:

How jQuery can create an animation effect that bounces when it hits the edge of the frame

jQuery's isPlainObject How to use the () method

The above is the detailed content of How to bind events to dynamically generated tags 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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!