简体   繁体   English

如何在JavaScript中使用函数作为另一个函数的参数

[英]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.

相关问题 在JavaScript中使用函数名作为另一个函数的参数是如何合法的? - How is it legal to use a function name as the argument to another function in JavaScript? 破解我的代码-如何在JavaScript中的另一个函数中使用函数名称作为参数 - Unbreak my code - how to use function name as an argument in another function in javascript QML:如何在另一个函数中传递javascript函数作为参数 - QML : how to pass javascript function as argument in another function 如何将参数从一个 function 传递到另一个 function onclick in javascript - How to pass a argument from one function to the another function onclick in javascript 使用javascript将参数传递给另一个函数(this) - Pass argument to another function with javascript (this) 如何使用一个函数的参数来调用另一个函数 - How to use an argument from one function to call another function 将带有参数的 function 作为参数传递给 JavaScript 中的另一个 function - Pass a function with parameter as an argument to another function in JavaScript 使用字符串作为函数的参数 (JavaScript) - Use string as argument of a function (JavaScript) 在 reduce 函数中使用函数参数:Javascript - Use function argument inside reduce function : Javascript 如何使用另一个JavaScript文件中定义的功能? - how to use a function defined in another javascript file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM