Sometimes, it is necessary to simulate user operations to achieve the click effect, such as after the user enters the page
Just trigger the click event without actively clicking.
For example, the following code:
<body> <a href="#" onclick="javascript:document.getElementById('d').innerHTML='x1'">点击1</a> <a href="#" onclick="javascript:document.getElementById('d').innerHTML='x2'">点击2</a> <a href="#" onclick="javascript:document.getElementById('d').innerHTML='x3'">点击3</a> </br> <span id="d"></span> </body>
The effect is that x1 will be displayed on the 'Click 1' page, and x2 will be displayed on the 'Click 2' page...
But it needs to be achieved that the first entry page is 'Click 1' by default
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 link A.
$('a').first().trigger("click");
In this way, when the page is loaded, the click event of the first A link is triggered, and the page will display x1
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 "myEvent" event to an element, the jQuery code is as follows:
$('#btn').bind("myEvent", function(){ alert("自定义事件"); });
To trigger this event, you can use the following code:
$('#btn').trigger("myEvent");
Pass data
trigger(type,[data]) method has two parameters,
The first one is the event object or the event type to be triggered,
The second parameter is an additional parameter passed to the event processing function, is passed in the form of an array. This is usually done by passing a parameter to
Callback function to distinguish whether this event is triggered by code or user.
The following is an example of passing data.
$('#btn').bind("myEvent", function(event,message1,message2){ alert(message1 + "," + message2); }); $('#btn').trigger("myEvent", ["Hello","World!"]);
The above is how to use jQuery to automatically trigger events. I hope it will be helpful to everyone's learning.