Home > Web Front-end > JS Tutorial > Usage analysis of trigger() and bind() in jQuery_jquery

Usage analysis of trigger() and bind() in jQuery_jquery

WBOY
Release: 2016-05-16 15:24:43
Original
1160 people have browsed it

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:

Copy code The code is as follows:
$("p").trigger("click")

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:

Please click here!


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!");
});

Copy after login

If you use trigger(), you have to write it like this:

$("#p1").click(function(){
  alert("hello!");
}).trigger(click);

Copy after login

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"]);

Copy after login

can also be written like this:

$("#p1").bind("myEvent",function(event,str1,str2) {
  alert(str1 + ' ' + str2);
}).trigger("myEvent",["Hello","World"]);

Copy after login

I hope this article will be helpful to everyone in jQuery programming.

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