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
Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

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 Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software