search
HomeWeb Front-endFront-end Q&AWhat are the ways to monitor jquery events?

jQuery provides four event monitoring methods: 1. Using bind(), you can add one or more event handlers to the selected element and set the event processing function; 2. Use live(), You can add one or more event handlers to the current or future matching elements and set the processing function; 3. Using delegate(), you can add one or more event handlers for the specified element (belonging to the child elements of the selected element) Program; 4. Using on(), you can add one or more event handlers on the selected element and sub-elements.

What are the ways to monitor jquery events?

The operating environment of this tutorial: windows7 system, jquery3.6 version, Dell G3 computer.

jQuery provides a variety of ways to bind events. Each method has its own characteristics. Understanding the similarities and differences between them will help us make the right choice when writing code, so as to write Produce elegant and easy-to-maintain code. Let's take a look at the ways to bind events in jQuery.

jQuery provides four event monitoring methods, namely bind, live, delegate, and on. The corresponding functions to unblock the monitoring are unbind, die, undelegate, and off

1. blind

Definition and usage: Add one or more event handlers to the selected element and specify the function to run when the event occurs.

Grammar:

$(selector).blind("事件类型",data,function(){});
//data是传入函数的参数用event.data获取(平时用的.click()等都是其简化用法)

Features

  • Applicable to static pages. It can only be bound to elements that already exist when it is called, and cannot be bound to new ones in the future. Added element binding

  • will only be blinded when the page is loaded;

Example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<script src="./js/jquery-3.6.0.min.js"></script>
		<script>
			$(document).ready(function() {
				$("p").bind("click", function() {
					console.log("这个段落被点击了。");
				});
			});
		</script>
	</head>
	<body>

		<p>点我!</p>

	</body>
</html>

What are the ways to monitor jquery events?

2, live

Definition: Add one or more event handlers to the current or future matching elements;

Syntax:

live("事件类型",data, 函数名);//data可选

Features: live does not bind the event to itself (this), but to this.context

It uses the event delegation mechanism to complete the monitoring and processing of events. The processing of the node is entrusted to the document

The newly added element does not need to be bound to a listener again and can be processed with multiple events

It can only be placed behind the directly selected element

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<script src="./js/jquery-1.7.2.min.js"></script>
		<script>
			$(document).ready(function() {
				$("button").live("click", function() {
					$("p").slideToggle();
				});
			});
		</script>
	</head>
	<body>

		<p>这是一个段落。</p>
		<button>点我!</button>
		<br><br>
	</body>
</html>

What are the ways to monitor jquery events?

Note: The live() method was deprecated in jQuery version 1.7 and removed in version 1.9. Please use the on() method instead.

3. delegate

delegate() method adds one or more event handlers to the specified element (belonging to the child elements of the selected element) and stipulates that when Functions that are run when these events occur.

Event handlers using the delegate() method apply to the current or future elements (such as new elements created by scripts).

Syntax:

delegate(selector,type,[data],fn)

Features: More precise use of event proxies in a small range, performance better than .live(). Can be used on dynamically added elements.

("父级选择器").delegate(".a","click",function())//表示:.a的事件通过父级元素进行委托,(this)获取的是触发事件的子元素

Example: When clicking the

element inside the

element, change the background color of all

elements

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<script src="./js/jquery-3.6.0.min.js"></script>
		<script>
			$(document).ready(function() {
				$("div").delegate("p", "click", function() {
					$("p").css("background-color", "pink");
				});
			});
		</script>
	</head>
	<body>

		<div style="background-color:yellow">
			<p>这个段落在 div 元素内。</p>
		</div>
		<p>这是一个段落。</p>

	</body>
</html>

What are the ways to monitor jquery events?

4, on

Definition: Bind the listening event to the nearest parent element

Syntax:

on(type, 选择器,方法)

Features:

  • You can also use event listening for newly added tags under the parent element

  • It also supports multi-time event processing

Example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<script ></script>
		<script>
			$(document).ready(function() {
				$("p").on("click", function() {
					console.log("段落被点击了。");
				});
			});
		</script>
	</head>
	<body>

		<p>点击这个段落。</p>

	</body>
</html>

What are the ways to monitor jquery events?

[Recommended learning: jQuery video tutorial, web front-end video]

The above is the detailed content of What are the ways to monitor jquery events?. 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
What are the limitations of React?What are the limitations of React?May 02, 2025 am 12:26 AM

React'slimitationsinclude:1)asteeplearningcurveduetoitsvastecosystem,2)SEOchallengeswithclient-siderendering,3)potentialperformanceissuesinlargeapplications,4)complexstatemanagementasappsgrow,and5)theneedtokeepupwithitsrapidevolution.Thesefactorsshou

React's Learning Curve: Challenges for New DevelopersReact's Learning Curve: Challenges for New DevelopersMay 02, 2025 am 12:24 AM

Reactischallengingforbeginnersduetoitssteeplearningcurveandparadigmshifttocomponent-basedarchitecture.1)Startwithofficialdocumentationforasolidfoundation.2)UnderstandJSXandhowtoembedJavaScriptwithinit.3)Learntousefunctionalcomponentswithhooksforstate

Generating Stable and Unique Keys for Dynamic Lists in ReactGenerating Stable and Unique Keys for Dynamic Lists in ReactMay 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript Fatigue: Staying Current with React and Its ToolsJavaScript Fatigue: Staying Current with React and Its ToolsMay 02, 2025 am 12:19 AM

JavaScriptfatigueinReactismanageablewithstrategieslikejust-in-timelearningandcuratedinformationsources.1)Learnwhatyouneedwhenyouneedit,focusingonprojectrelevance.2)FollowkeyblogsliketheofficialReactblogandengagewithcommunitieslikeReactifluxonDiscordt

Testing Components That Use the useState() HookTesting Components That Use the useState() HookMay 02, 2025 am 12:13 AM

TotestReactcomponentsusingtheuseStatehook,useJestandReactTestingLibrarytosimulateinteractionsandverifystatechangesintheUI.1)Renderthecomponentandcheckinitialstate.2)Simulateuserinteractionslikeclicksorformsubmissions.3)Verifytheupdatedstatereflectsin

Keys in React: A Deep Dive into Performance Optimization TechniquesKeys in React: A Deep Dive into Performance Optimization TechniquesMay 01, 2025 am 12:25 AM

KeysinReactarecrucialforoptimizingperformancebyaidinginefficientlistupdates.1)Usekeystoidentifyandtracklistelements.2)Avoidusingarrayindicesaskeystopreventperformanceissues.3)Choosestableidentifierslikeitem.idtomaintaincomponentstateandimproveperform

What are keys in React?What are keys in React?May 01, 2025 am 12:25 AM

Reactkeysareuniqueidentifiersusedwhenrenderingliststoimprovereconciliationefficiency.1)TheyhelpReacttrackchangesinlistitems,2)usingstableanduniqueidentifierslikeitemIDsisrecommended,3)avoidusingarrayindicesaskeystopreventissueswithreordering,and4)ens

The Importance of Unique Keys in React: Avoiding Common PitfallsThe Importance of Unique Keys in React: Avoiding Common PitfallsMay 01, 2025 am 12:19 AM

UniquekeysarecrucialinReactforoptimizingrenderingandmaintainingcomponentstateintegrity.1)Useanaturaluniqueidentifierfromyourdataifavailable.2)Ifnonaturalidentifierexists,generateauniquekeyusingalibrarylikeuuid.3)Avoidusingarrayindicesaskeys,especiall

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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.