Home >Web Front-end >JS Tutorial >Usage sharing: How to use jQuery to automatically trigger events trigger
This article mainly introducesjQueryHow to use the automatic trigger event trigger. Friends who need it can refer to it
Sometimes, it is necessary to simulate user operations to achieve the click effect. For example, after the user enters the page,
triggers 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 is necessary to realize that the default for entering the page for the first time is 'Click 1'
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 link A.
$('a').first().trigger("click");
In this way, when the page is loaded, it will trigger For the click event of the first A link, the page will display Supported events with the same name can 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("自定义事件");
});
If you want to trigger this event, you can use the following code to achieve it:
$('#btn').trigger("myEvent");
Pass data
trigger(type,[ data]) method has two parameters,
The first is the event object or the event type to be triggered, The second parameter is the additional parameter passed to the event processing function , Passed in array form. 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.
$('#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 event trigger. I hope it will be helpful to everyone's learning.
The above is the detailed content of Usage sharing: How to use jQuery to automatically trigger events trigger. For more information, please follow other related articles on the PHP Chinese website!