Home > Article > Web Front-end > Usage analysis of trigger() and bind() in jQuery_jquery
The examples in this article describe the usage of trigger() and bind() in jQuery. Share it with everyone for your reference, the details are as follows:
trigger(type)
Trigger some type of event on each matching element.
Return value:jQuery
Parameters:
type (String): The type of event to be triggered
Example:
1.trigger() trigger event
This method is a new function in jQuery 1.3 that causes trigger events.
The events here are just like the events column in jQuery's help document, such as click, mouseover, keydown and other js events with actions, while show and hide are effects and not events.
2. Why use trigger()?
I believe everyone has this idea when they first come into contact?
For example, on the front page there is: bd38f46914269f40e05faa352becc824 Please click here! 94b3e26ee717c64999d7867364b1b4a3
You want to execute this event when the page is loaded and bind the click event to this p (write the following code in $(function(){});):
$("#p1").click(function(){ alert("hello!"); });
If you use trigger(), you have to write it like this:
$("#p1").click(function(){ alert("hello!"); }).trigger(click);
Wouldn’t it be more troublesome to write like this? It can be said that, but the biggest advantage of using trigger() is that it can pass parameters in. For example:
//myEvent为自定义事件名 $("#p1").bind("myEvent",function(event,str1,str2) { alert(str1 + ' ' + str2); }); $("#p1").trigger("myEvent",["Hello","World"]);
can also be written like this:
$("#p1").bind("myEvent",function(event,str1,str2) { alert(str1 + ' ' + str2); }).trigger("myEvent",["Hello","World"]);
I hope this article will be helpful to everyone in jQuery programming.