The example in this article describes how JQuery automatically triggers events. Share it with everyone for your reference. The details are as follows:
Common simulations
Sometimes, it is necessary to simulate user operations to achieve the click effect. For example, after the user enters the page, the click event is triggered without the user having to actively click.
In JQuery, you can use the trigger() method to complete simulation operations. For example, you can use the following code to trigger the click event of the button with id btn.
$('#btn').trigger("click");
In this way, when the page is loaded, the desired effect will be output immediately. You can also directly abbreviate click() to achieve the same effect:
$('#btn').click();
Trigger custom event
Thetrigger() method can not only trigger events with the same name supported by the browser, but also trigger events with custom names. For example, to bind a "myClick" event to an element, the JQuery code is as follows:
$('#btn').bind("myClick", function(){ $('#test').append("<p>我的自定义事件.</p>"); });
To trigger this event, you can use the following code:
$('#btn').trigger("myClick");
Pass data
Thetrigger(type[,data]) method has two parameters. The first parameter is the event type to be triggered, and the second parameter is the additional data to be passed to the event processing function, passed in the form of an array. You can usually distinguish whether this event is triggered by code or user by passing a parameter to the callback function.
The following is an example of passing data.
$(function(){ $('#btn').bind("myClick", function(event, message1, message2){ $('#test').append( "<p>"+message1 + message2 +"</p>"); }); $('#btn').click(function(){ $(this).trigger("myClick",["我的自定义","事件"]); }).trigger("myClick",["我的自定义","事件"]); })
Perform default action
After the trigger() method triggers an event, the browser's default operation will be performed. For example:
$("input").trigger("focus");
The above code will not only trigger the focus event bound to the element, but also cause the element itself to get focus (this is the browser's default operation).
If you only want to trigger the bound focus event without performing the browser's default operation, you can use another similar method in jQuery - the triggerHandler() method.
$("input").triggerHandler("focus");
This method will trigger the specific event bound to the element, and at the same time cancel the browser's default operation for this event, that is, the text box will only trigger the bound focus event and will not receive focus.
I hope this article will be helpful to everyone’s jQuery programming.