Home > Web Front-end > JS Tutorial > How to use jQuery to automatically trigger events trigger_jquery

How to use jQuery to automatically trigger events trigger_jquery

WBOY
Release: 2016-05-16 15:29:06
Original
1235 people have browsed it

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

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

The

trigger() 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("自定义事件");
});
Copy after login

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!"]);
Copy after login

The above is how to use jQuery to automatically trigger events. I hope it will be helpful to everyone's learning.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template