Home >Web Front-end >JS Tutorial >Usage sharing: How to use jQuery to automatically trigger events trigger

Usage sharing: How to use jQuery to automatically trigger events trigger

巴扎黑
巴扎黑Original
2017-06-25 13:29:161370browse

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(&#39;d&#39;).innerHTML=&#39;x1&#39;">点击1</a>
  <a href="#" onclick="javascript:document.getElementById(&#39;d&#39;).innerHTML=&#39;x2&#39;">点击2</a>
  <a href="#" onclick="javascript:document.getElementById(&#39;d&#39;).innerHTML=&#39;x3&#39;">点击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:

$(&#39;#btn&#39;).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.

$(&#39;#btn&#39;).bind("myEvent", function(event,message1,message2){ 
  alert(message1 + "," + message2);
});
$(&#39;#btn&#39;).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!

Statement:
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