在事件监听器函数中传递参数 [英] Pass Argument In Event Listener Function
本文介绍了在事件监听器函数中传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将一个参数传递给在事件侦听器内部被调用的函数.下面的代码显示了我想做的事情,但是它并没有让我按常规进行.有什么解决方法?
I want to pass an argument to the function that is being called inside of the event listener. The code below shows what I want to do however it is not letting me do it conventionally. What is a workaround to this?
HTML代码:
<button id='btn'>Click Me</button>
JavaScript代码:
JavaScript code :
<script>
document.getElementById('btn').addEventListener( "click",btnClick(5) );
function btnClick(argument)
{
console.log("Button clicked with argument : " + argument);
}
</script>
控制台应显示为:
Button clicked with argument : 5
谢谢大家.
推荐答案
具有匿名功能
document.getElementById('btn').addEventListener( "click", function() {
btnClick(5);
}, false );
如果您需要保留 this
的值,则可以使用call或apply
If you need to keep the value of this
you can use call or apply
btnClick.call(this, 5);
这篇关于在事件监听器函数中传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文