[英]how to use a function as a argument of another function in javascript
<input type="button" id="one" value="1" OnClick='addValue("function(){document.getElementById("one")}")'>
I want to pass the id of this input as argument of addValue function. 我想将此输入的ID作为addValue函数的参数传递。 Where is the mistake here ? 这里的错误在哪里?
您太复杂了,使用this
<input type="button" id="one" value="1" OnClick='addValue(this.id)'>
First, move the event listener out of the HTML and then you can access the value from the click events target. 首先,将事件监听器移出HTML,然后可以从单击事件目标中访问该值。
document.getElementById('one').addEventListener('click', function(evt) {
var value = evt.target.value;
addValue(value);
});
Edit: or use @tymeJV's solution, though I'd recommend getting away from inline events. 编辑:或使用@tymeJV的解决方案,尽管我建议远离内联事件。
If you really want to use function as argument of another function then have a look at anonymous functions http://en.wikibooks.org/wiki/JavaScript/Anonymous_Functions , SetTimeout is a good example, you pass a function as an argument to it to call after specific time. 如果您真的想将函数用作另一个函数的参数,然后看看匿名函数http://en.wikibooks.org/wiki/JavaScript/Anonymous_Functions ,则SetTimeout是一个很好的例子,您可以将函数作为参数传递给它在特定时间后致电。
But I think you can accomplish this without passing function as argument as mentioned in the answer of @tymeJV. 但是我认为您可以在不传递函数作为@tymeJV答案中提到的参数的情况下完成此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.