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 id="p1">请点击这里!</p> 

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

      $("#p1").click(function(){

                alert("hello!");

            });

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

            $("#p1").click(function(){

                alert("hello!");

            }).trigger(click);

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

        //myEvent为自定义事件名

        $("#p1").bind("myEvent",function(event,str1,str2) {

               alert(str1 + ' ' + str2); 

          });  

         $("#p1").trigger("myEvent",["Hello","World"]); 

也可以这样写:

    $("#p1").bind("myEvent",function(event,str1,str2) {

               alert(str1 + ' ' + str2); 

          }).trigger("myEvent",["Hello","World"]); 

 
 
原文地址:https://www.cnblogs.com/mgqworks/p/7714573.html