Home Web Front-end JS Tutorial How to bind events to dynamically generated tags in jquery

How to bind events to dynamically generated tags in jquery

Mar 14, 2018 pm 04:31 PM
jquery Label generate

This time I will bring you jqueryHow to bind dynamically generated tagsEvents, jqueryNotes on binding events to dynamically generated tags What 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:

	<body>
		<!-- 下面是用纯动态方式生成标签 -->
		<p id="d2">
			生成a标签
		</p>
		<p id="d3">
			<input type="button" value="生成a标签" id="btn" />
		</p>
	</body>
	<script>		
		$(function(){
			$('#btn').bind('click', function(event) {
			 /* 在添加标签的同时给添加的标签绑定点击事件 */
			 $("<li>Hello</li>").appendTo("#d2");
 			});
 			
 			///bind方法对于动态添加的标签不好使,只对已经存在的静态标签好用
 			$('li').bind('click', function(event) {
			 alert("haha"); ///根本不会触发这个方法
 			});
		})
	</script>
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:

<body>
		<!-- 下面是用纯动态方式生成标签 -->
		<p id="d2">
			动态生成a标签
		</p>
		<p id="d3">
			<input type="button" value="生成a标签" id="btn"/>
			
		</p>
	</body>
	<script>
		$(function() {
			///点击按钮,给d2动态添加标签
			$('#btn').bind('click', function() {
				/* 在添加标签的同时给添加的标签绑定点击事件 */
				$("<li onclick=&#39;show()&#39;>Hello</li>").appendTo("#d2");
			});
	
		})
	
		function show() {
			alert($(this).text());///这样打印出的是空的,没有任何东西,但是方法是会触发的(不能这样打印自己)
			alert("哈哈");
		}
	</script>
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:

	<body>
		<!-- 下面是用纯动态方式生成标签 -->
		<p id="d2">
			生成a标签
		</p>		
		<p id="d3">
			<input type="button" value="生成a标签" id="btn"/>
		</p>
	</body>
	<script>
		$(function(){
			$('#btn').bind('click', function(event) {
			 /* 在添加标签的同时给添加的标签绑定点击事件 */
			 $("<li>Hello</li>").appendTo("#d2").bind('click', function() {
			  /* 显示标签的内容 */
			  alert($(this).text()); ///这种方式也可以正常打印出 hello
			 });
 			}); 			
		})
	</script>
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:

<body>
		<!-- 下面是用纯动态方式生成标签 -->
		<p id="d1">
			测试静态标签的绑定方法
		</p>
		<br />		
		<p id="d2">
			动态生成a标签的位置
		</p>
		<p id="d3">
			<input type="button" value="生成a标签" id="btn" />
		</p>
	</body>
	<script>
		$(function(){
			$('#btn').bind('click', function() {
			 /* 在添加标签的同时给添加的标签绑定点击事件 */
			 $("<li>Hello</li>").appendTo("#d2");
 			});			
 			///bind方法对于动态添加的标签不好使,只对已经存在的静态标签好用
 			///用live方法才好用
 			$('li').live('click', function() {
			 alert($(this).text());///注意,用live还可以这样写,结果是正常的
			 alert("haha");
 			}); 			
 			///通过 live() 方法附加的事件处理程序适用于匹配选择器的当前及未来的元素(比如由脚本创建的新元素)
 			$('#d1').live('click', function() {///对于静态和动态创建的标签都好使
			 alert($(this).text());///注意,用live还可以这样写,结果是正常的.这是非常重要的
			 alert("haha");
 			});
		})
	</script>
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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

What is the clock behind the TikTok label? How to tag Douyin account? What is the clock behind the TikTok label? How to tag Douyin account? Mar 24, 2024 pm 03:46 PM

When browsing Douyin works, we often see a clock icon behind the tag. So, what exactly is this clock? This article will focus on the discussion of &quot;What is the clock behind the Douyin label&quot;, hoping to provide some useful reference for your use of Douyin. 1. What is the clock behind the Douyin label? Douyin will launch some hot topic challenges. When users participate, they will see a clock icon after the tag, which means that the work is participating in the topic challenge and displays the remaining time of the challenge. For some time-sensitive content, such as holidays, special events, etc., Douyin will attach a clock icon after the label to remind users of the validity period of the content. 3. Popular tags: When a tag becomes popular, Douyin will add a clock icon after the tag to indicate that the tag is

How to add tags on Douyin to attract traffic? Which tags on the platform are easiest to attract traffic to? How to add tags on Douyin to attract traffic? Which tags on the platform are easiest to attract traffic to? Mar 22, 2024 am 10:28 AM

As a popular short video social platform, Douyin has a huge user base. For Douyin creators, using tags to attract traffic is an effective way to increase the exposure of content and attract attention. So, how does Douyin use tags to attract traffic? This article will answer this question in detail for you and introduce related techniques. 1. How to add tags on Douyin to attract traffic? When posting a video, make sure to choose tags that are relevant to the content. These tags should cover the topic and keywords of your video to make it easier for users to find your video through tags. Leveraging popular hashtags is an effective way to increase your video’s exposure. Research current popular tags and trends and incorporate them into your video descriptions and tags. These popular tags usually have higher visibility and can attract the attention of more viewers. 3. Label

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

See all articles