search
HomeWeb Front-endJS TutorialDetailed explanation of jQuery.triggerHandler() function

Detailed explanation of jQuery.triggerHandler() function

Jun 25, 2017 pm 02:24 PM
functionDetailed explanation

triggerHandler() function is used to trigger an event of the specified type on each matching element.

In addition, you can also pass in additional parameters to the event handling function when the event is triggered.

The function of this function is similar to the trigger() function, but the triggerHandler() function has the following exceptions:

triggerHandler() will not trigger the default behavior of the execution element (such as the default link click event Jump behavior, default submission behavior of form submit event).

triggerHandler() triggers events only for the first matching element in the jQuery object.

Events triggered by triggerHandler() do not bubble up in the DOM tree, so the event does not bubble up to any of its ancestor elements.

The return value of triggerHandler() is the return value of the corresponding event processing function, not the current jQuery object itself.

This function belongs to the jQuery object (instance).

Syntax

jQuery 1.2 Added this function.

jQueryObject.triggerHandler( events [, extraArguments ] )

Parameters

Parameter Description

events String type specifies the event type and optional Namespace, such as "click", "focus", "keydown.myPlugin".

extraArguments Optional/Object type is the extra parameters passed in by the event processing function. If you want to pass in multiple parameters, please pass them in as an array.

ThetriggerHandler() function will pass in a default parameter for the event processing function that triggers execution, which is the Event object representing the current event.

The parameter extraArguments is used to pass in more additional parameters to the event handling function. If extraArguments is in array form, each element will serve as a parameter to the function.

Return value

The return value of the triggerHandler() function is of any type and returns the return value of the event processing function that triggered execution.

Example & Description

Please refer to the following initial HTML code:

<input id="btn1" type="button" value="点击1" />
<input id="btn2" type="button" value="点击2" />
<a id="a1" href="#">CodePlayer</a>
<div id="log"></div>

First, we bind events to the above button and elements, and then use triggerHandler () function directly triggers events, the corresponding code is as follows:

var $log = $("#log");
function handler( event, arg1, arg2 ){
    var html = &#39;<br>触发元素#&#39; + this.id + &#39;的[&#39; + event.type +&#39;]事件,额外的函数参数为:&#39; + arg1 + &#39;, &#39; + arg2;
    $log.append( html );
}
var $buttons = $(":button");
// 为所有button元素的click事件绑定事件处理函数
$buttons.bind( "click", handler );
// 为所有a元素的click、mouseover、mouseleave事件绑定事件处理函数
$("a").bind( "click mouseover mouseleave", handler );
// 触发btn1的click事件
// 虽然$buttons匹配两个button元素,但只会触发第一个匹配元素的click事件
$buttons.triggerHandler("click");
/*(追加文本)
触发元素#btn1的[click]事件,额外的函数参数为:undefined, undefined
*/
$("#btn2").triggerHandler("click", "CodePlayer");
/*(追加文本)
触发元素#btn2的[click]事件,额外的函数参数为:CodePlayer, undefined
*/
// arg1 = "张三", arg2 = 20
$("a").triggerHandler("mouseover", ["张三", 20 ] );
/*(追加文本)
触发元素#a1的[mouseover]事件,额外的函数参数为:张三, 20
*/
$("a").triggerHandler("mouseleave", { name: "张三", age: 18 } );
/*(追加文本)
触发元素#a1的[mouseleave]事件,额外的函数参数为:[object Object], undefined
*/

Running code (please copy other codes to the demo page to run)

triggerHandler() function can also handle functions based on incoming events Event object to trigger the corresponding event.

var $btn1 = $("#btn1");
// 为btn1元素的click事件绑定事件处理函数
$btn1.bind( "click", function(event){
    alert("click1");    
});
// 为btn1元素的click事件绑定事件处理函数
// 如果传入了一个有效的额外参数,则再次触发click
$btn1.bind( "click", function(event, arg1){
    alert("click2");
    if(arg1)
        $(this).triggerHandler( event );
});
// $btn1.triggerHandler( "click" ); // 调用一次click1、调用一次click2
$btn1.triggerHandler( "click", true ); // 调用两次click1、调用两次click2
此外,triggerHandler()函数还可以只触发包含指定定命名空间的事件(1.4.3+才支持命名空间)。
function A( event ){
    alert( &#39;A&#39; );
}
function B( event ){
    alert( &#39;B&#39; );
}
function C( event ){
    alert( &#39;C&#39; );
}
var $btn1 = $("#btn1");
// 为btn1元素的click事件绑定事件处理函数
$btn1.bind( "click.foo.bar", A );
$btn1.bind( "click.test.foo", B );
$btn1.bind( "click.test", C );
// 触发btn1的click事件,不限定命名空间
$btn1.triggerHandler("click"); // 触发A、B、C
// 触发btn1的包含命名空间foo的click事件
$btn1.triggerHandler("click.foo"); // 触发A、B
// 触发btn1的包含命名空间test的click事件
$btn1.triggerHandler("click.test"); // 触发B、C
// 触发btn1的同时包含命名空间foo和test的click事件
$btn1.triggerHandler("click.foo.test"); // 触发B

The above is the detailed content of Detailed explanation of jQuery.triggerHandler() function. 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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use