jQuery事件之传递参数

来源:互联网 发布:net程序员工资 编辑:程序博客网 时间:2024/05/22 15:38

我们经常使用jQuery中给DOM元素绑定事件来执行一些动态的功能,但是很少有人知道在jQuery中是如何来给DOM元素传递参数以及如何绑定自己定义的事件。

   这次依然在Firefox中的firebug来测试这些功能。在我的页面中有P标签,input标签(type=button)和一个img标签;
    1:传递参数:
        A:使用trigger来触发事件:
             $('p:first').bind('myclick',function(event,arg1,arg2){
             //第一参数event,是事件必须的,没有pageX这些属性;可以使用console.log(event)来查看
                 $(arg1).appendTo('body');
                 console.log(arg2);
                 });
             $('input').click(function(){
                 $('p:first').trigger('myclick',//这里触发了myclick事件
                  ['<div><a href="http://www.google.com.hk">google</a></div>',//第一个参数 DOM
                   'this is to console.log']); //第二个参数 string
                 });
        B:使用bind来传递参数:
            原形: bind('事件'[,参数],函数);
            在这里参数被当做event.data的值来处理的,参数可以使任何格式的;该例为JSON格式的。
            var name_value='stonecold';
            $('p').bind('click',{name:name_vlaue},function(event){
                    //event和A中的解释一样
                 console.log(event.data.name);//结果在控制台上显示为stonecold
                   });
    2:事件相同命名空间不同事件:
         在这里我们绑定了一个命名空间:spacename,这个命名空间有点特殊,在后面
         $('img:first').bind('click.spacename',function(){
             console.log('this is the click event for spacename ');
            });
         $('img:first').bind('mouseenter.spacename',function(){
            console.log('this is the mouseenter event for spacename');
            });
         $('img:first').bind('click ',function(){
             console.log('this is the click event without spacename ');
            });
         拆除在命名空间spacename下的所有的事件。即click这个事件还可以使用 ,命名空间前要有点。
        $('img:first').unbind('.spacename');
    3:相同的事件名不同的命名空间:
        $('img:first').bind('click.spacename',function(){
             console.log('this is the click event for spacename ');
            });
        $('img:first').bind('click',function(){
             console.log('this is the click event without spacename');
            });
    在这里如果使用上例中的bind这个函数的话是不起作用的,在这里使用trigger函数,使用后面的感叹号是不会触发有命名空间的事件。
       $('input').click(function(){
             $('img:first').trigger('click! ');
            });
    4:在简单的事件中传递参数:
       所谓的简单事件就是使用click这种格式,不是使用bind这种格式;
       在这种事件中不能直接传递参数,可以利用闭包这种JavaScript特性来传递参数;
       A:首先定义一个函数,在点击的时候触发:
          function fn_name(arg1){
           $(arg1).appendTo('body');
               }
       B:定义一个变量作为参数传递
          var arg='<a href="http://www.google.com.hk">google<a>';
          $('img:first').click(function(){
             fn_name(arg);
              });
        这样就可以在事件中传递参数了;

http://blog.sina.com.cn/s/blog_66a13c610100i3pj.html  

原创粉丝点击