js 点击事件回调函数传参

来源:互联网 发布:刘备汉昭烈帝皮肤优化 编辑:程序博客网 时间:2024/05/17 12:51

点击事件回调函数传参

使用匿名函数


function testFun(event, str) {console.log(str);}var test = document.getElementById('test');test.addEventListener('click', function(event) {testFun(event, 'this is a test');});

上面的例子给元素绑定点击事件函数的时候,使用了匿名函数,在匿名函数里面再调用testFun函数,这样可以方便给testFun函数传入参数,但这个方法看起来是那么的傻,最致命的是无法给元素解绑点击事件处理函数,实为下策!

使用bind方法


function testFun(str, event) {console.log(str);console.log(event.target === this);}var test = document.getElementById('test');test.addEventListener('click', testFun.bind(test, 'this is a test'));

上面的例子中,使用bind方法来给testFun函数指定this值和参数,这样也能达到给回调函数传入参数的效果,看起来会更优雅一点。但值得注意的是回调函数的最后的一个参数才是event对象。同时,这个方法依然无法解绑事件处理函数,且在IE9以下不被支持。

JQuery方法


function testFun(event, str) {console.log(event.data.str);$(this).unbind('click', testFun);}$('#test').click({str: 'this is a test'}, testFun);

上面是使用jQuery的方法,注意,如果click事件不用传入第一个参数,那么就会当成一个模拟click事件。此方法将click第一个参数当成了event对象的一个data属性,在事件处理函数中就能够使用到传入参数,最主要的是可以通过jQuery本身的unbind方法解绑事件处理函数。
原创粉丝点击