search
HomeWeb Front-endJS TutorialHow to bind events to dynamically generated tags in jquery

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:

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

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:

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

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:

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

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:

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

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
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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.