jQuery事件之传递参数

 2023-09-07 阅读 24 评论 0

摘要:jQuery事件之传递参数 转载▼ 我们经常使用jQuery中给DOM元素绑定事件来执行一些动态的功能,但是很少有人知道在jQuery中是如何来给DOM元素传递参数以及如何绑定自己定义的事件。 这次依然在Firefox中的firebug来测试这些功能。在我的页面中有P标签,input标签(

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

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/10928.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息