jQuery事件之传递参数

jQuery事件之传递参数


       我们经常使用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函数,使用后面的感叹号是不会

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值