Home Web Front-end JS Tutorial jQuery.trigger() function usage tutorial

jQuery.trigger() function usage tutorial

Jun 25, 2017 am 11:18 AM
use function Tutorial

trigger() 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.

Using this function can manually trigger the execution of the event processing function bound to the element, and will also trigger the execution of the default behavior of the element.

Taking the form element

as an example, using trigger("submit") can trigger the submit event bound to the form, and also execute the default behavior of the form submit event - the form submission operation.

According to feedback from netizen @Feiyang, the trigger("click") of the link tag is a special case and will not trigger the default behavior of the link click event - jump to the operation of the corresponding link, click View related details here.

Starting from jQuery 1.3, events triggered by the trigger() function also support event bubbling, which can be bubbled and passed to the DOM tree.

This function belongs to the jQuery object (instance).

Syntax

The trigger() function mainly has the following two forms of usage:

Usage 1:

jQueryObject.trigger( events [, extraArguments ] )

Trigger events of the specified type (events) on each matching element, and can pass in additional parameters (extraArguments) to the event handling function.

Usage 2: jQuery 1.3 newly supports this usage.

jQueryObject.trigger( eventObject [, extraArguments ] )

is the Event object (eventObject) passed in by the specified event processing function, which is used to trigger the execution of the corresponding event processing function and can be used for events The processing function passes in extra parameters (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.

eventObject Object type is an Event object, used to trigger the event processing function passed in to the object.

Thetrigger() 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

trigger()The return value of the function is of jQuery type and returns the current jQuery object itself.

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>
Copy after login

First, we bind events to the above button and elements, and then use trigger () 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 );
// 触发所有button的click事件
$buttons.trigger("click"); 
/*(追加文本)
触发元素#btn1的[click]事件,额外的函数参数为:undefined, undefined
触发元素#btn2的[click]事件,额外的函数参数为:undefined, undefined
*/
$("#btn1").trigger("click", "CodePlayer");
/*(追加文本)
触发元素#btn1的[click]事件,额外的函数参数为:CodePlayer, undefined
*/
// arg1 = "张三", arg2 = 20
$("a").trigger("mouseover", ["张三", 20 ] );
/*(追加文本)
触发元素#a1的[mouseover]事件,额外的函数参数为:张三, 20
*/
$("a").trigger("mouseleave", { name: "张三", age: 18 } );
/*(追加文本)
触发元素#a1的[mouseleave]事件,额外的函数参数为:[object Object], undefined
*/
trigger()函数还可以根据传入事件处理函数的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).trigger( event );
});
// $btn1.trigger( "click" ); // 调用一次click1、调用一次click2
$btn1.trigger( "click", true ); // 调用两次click1、调用两次click2

In addition, the trigger() function can also trigger only events containing a specified namespace (namespaces are supported only in 1.4.3+).

The above is the detailed content of jQuery.trigger() function usage tutorial. 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)

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

In summer, you must try shooting a rainbow In summer, you must try shooting a rainbow Jul 21, 2024 pm 05:16 PM

After rain in summer, you can often see a beautiful and magical special weather scene - rainbow. This is also a rare scene that can be encountered in photography, and it is very photogenic. There are several conditions for a rainbow to appear: first, there are enough water droplets in the air, and second, the sun shines at a low angle. Therefore, it is easiest to see a rainbow in the afternoon after the rain has cleared up. However, the formation of a rainbow is greatly affected by weather, light and other conditions, so it generally only lasts for a short period of time, and the best viewing and shooting time is even shorter. So when you encounter a rainbow, how can you properly record it and photograph it with quality? 1. Look for rainbows. In addition to the conditions mentioned above, rainbows usually appear in the direction of sunlight, that is, if the sun shines from west to east, rainbows are more likely to appear in the east.

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

What is Bitget Launchpool? How to use Bitget Launchpool? What is Bitget Launchpool? How to use Bitget Launchpool? Jun 07, 2024 pm 12:06 PM

BitgetLaunchpool is a dynamic platform designed for all cryptocurrency enthusiasts. BitgetLaunchpool stands out with its unique offering. Here, you can stake your tokens to unlock more rewards, including airdrops, high returns, and a generous prize pool exclusive to early participants. What is BitgetLaunchpool? BitgetLaunchpool is a cryptocurrency platform where tokens can be staked and earned with user-friendly terms and conditions. By investing BGB or other tokens in Launchpool, users have the opportunity to receive free airdrops, earnings and participate in generous bonus pools. The income from pledged assets is calculated within T+1 hours, and the rewards are based on

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

See all articles