JQuery simulates click events to automatically trigger events
Sometimes, you need to simulate user operations to achieve the effect of clicking. For example, when a user enters the page, the click event is triggered without the user clicking it.
In JQuery, you can use the trigger () method to complete the simulation operation. For example, you can use the following code to trigger the click Event of a button with the id of btn.
$('#btn').trigger("click");
In this way, after the page is loaded, the desired effect will be immediately output. You can also simply use click () to achieve the same effect:
$('#btn').click();
Trigger custom events
The trigger () method triggers events with the same name and custom names supported by the browser. For example, if you bind an "myClick" event to an element, the JQuery code is as follows:
$ ('# Btn '). bind ("myClick", function () {$ ('# test '). append ("<p> my custom events. </p> ");});
To trigger this event, use the following code:
$('#btn').trigger("myClick");
Transmit data
The trigger (type [, data]) method has two parameters: 1st are the event type to be triggered, and 2nd are the additional data to be passed to the event processing function, transmitted as an array. Generally, you can pass a parameter to the callback function to identify whether the event is triggered by code or by the user.
The following is an example of data transmission.
$ (Function () {$ ('# btn '). bind ("myClick", function (event, message1, message2) {$ ('# test '). append ("<p>" + message1 + message2 + "</p>") ;}; $ ('# btn '). click (function () {$ (this ). trigger ("myClick", ["my custom", "Event"]);}). trigger ("myClick", ["my custom", "Event"]);})
Perform default operations
When the trigger () method triggers an event, the default browser operation is performed. For example:
$("input").trigger("focus");
The above code triggers not only the focus event bound to the <input> element, but also the focus of the <input> element itself (this is the default operation of the browser ).
If you only want to trigger the bound focus event and do not want to perform the default operations on the browser, you can use the triggerHandler () method, which is similar to the method in jQuery.
$("input").triggerHandler("focus");
This method triggers a specific event bound to the <input> element, and cancels the default action of the browser on this event. That is, the text box only triggers the bound focus event and does not get the focus.