Home > Web Front-end > JS Tutorial > body text

jQuery中trigger()与bind()用法分析_jquery

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

本文实例讲述了jQuery中 trigger()与bind()用法。分享给大家供大家参考,具体如下:

trigger(type)

在每一个匹配的元素上触发某类事件。

返回值:jQuery

参数:

type (String): 要触发的事件类型

示例:

复制代码 代码如下:
$("p").trigger("click")

1.trigger() 触发事件

这个方法是jQuery 1.3中新增的一个引起触发事件的函数。
这里的事件就如jQuery的帮助文档中的事件那一栏,如:click, mouseover, keydown 等有动作的js事件,而像show, hide这是效果不是事件。

2.为什么要用 trigger() ?

相信刚开始接触大家也都有这样的想法?

比如前台页面里有:

请点击这里!


你希望加载页面时就执行这个事件给这个这p绑定了click事件(将下面的代码写在$(function(){});里面):
$("#p1").click(function(){
  alert("hello!");
});

Copy after login

如果用trigger(),你就要写成这样:

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

Copy after login

这样写不是更加麻烦了吗?可以这么说,但是用trigger()最大的好处就是它是可以传递参数进去的。例如:

//myEvent为自定义事件名
$("#p1").bind("myEvent",function(event,str1,str2) {
  alert(str1 + ' ' + str2); 
});
$("#p1").trigger("myEvent",["Hello","World"]);

Copy after login

也可以这样写:

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

Copy after login

希望本文所述对大家jQuery程序设计有所帮助。

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!