[英]How do I pass an argument to referenced function without invoking it using Javascript
I want my code to be something like el.onclick = someFunc(arg)
, however, someFunc is invoked on load. 我希望我的代码类似于
el.onclick = someFunc(arg)
,但是,在加载时调用someFunc。 How would I go about passing an argument to a function that I want to reference, without also invoking it? 我该如何在不调用参数的情况下将参数传递给要引用的函数呢?
Try using the addEventListener
to add the event click. 尝试使用
addEventListener
添加事件单击。 The addEventListener
method attaches an event handler to the specified element. addEventListener
方法将事件处理程序附加到指定的元素。 You need to pass the callback, which would be invoked when the event occurs. 您需要传递回调,事件发生时将调用该回调。
movieElement.addEventListener("click", function(){
showDescription(arg);
});
You can do this in following 3 ways, 您可以通过以下3种方式进行操作:
addEventListener
addEventListener
var elm = document.getElementById('testButton'); elm.addEventListener('click', function(){ someFunc('testArg'); }); function someFunc(arg) { console.log(arg); }
<input id="testButton" type="button" value="Click" />
onclick
and bind
onclick
和bind
function someFunc(arg) { console.log(arg); } var elm = document.getElementById('testButton'); elm.onclick = someFunc.bind(null, 'testArg');
<input id="testButton" type="button" value="Click" />
onclick
and function wrapper, onclick
和函数包装器, function someFunc(arg) { return function() { console.log(arg); } } var elm = document.getElementById('testButton'); elm.onclick = someFunc('testArg');
<input id="testButton" type="button" value="Click" />
Note : Option 1 with addEventListener
is the best one to use among the options above but other options (1 & 2) can be considered in case of option 1 is not doable. 注意 :在上述选项中,带有
addEventListener
选项1是最好的选择,但在选项1无效的情况下,可以考虑其他选项(1&2)。
For an instance, you can use onclick
and bind
when you need to reuse the same method for multiple elements and have to use the element inside the method with this
as below. 对于一个实例,可以使用
onclick
和bind
时需要重用多个元素相同的方法,并具有使用该方法内部的元件与this
如下。
var buttons = document.getElementsByTagName('input'); for(var i = 0; i < buttons.length; i++) { var button = buttons[i]; button.onclick = someFunc.bind(button, 'testArg'); } // Assume this function is in another file function someFunc(arg) { console.log(this.id + ': '+ arg); }
<div> <input id="testButton1" type="button" value="Click" /> <input id="testButton2" type="button" value="Click" /> <input id="testButton3" type="button" value="Click" /> <input id="testButton4" type="button" value="Click" /> <input id="testButton5" type="button" value="Click" /> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.