![](/img/trans.png)
[英]How to pass additional arguments to callback functions in javascript when using .execute()?
[英]How to execute a callback with custom arguments in JavaScript
JS中是否有一种方法可以执行带有自定义参数(而不是完全没有参数)的回调,例如:
btn.onclick = displayText
要么
operation.onComplete(displayText)
在这里,我希望使用诸如displayText("Hello World")
类的参数而不是默认的displayText()
来调用回调displayText
。
您可以使用apply
或call
来调用带有参数的方法。
btn.onclick = function() {
displayText.call(null, "Hello World", arg1, arg2...);
}
btn.onclick = function() {
displayText.apply(null, ["Hello World", arg1, arg2, ...]);
}
function displayText(arg1) {
console.log(arg1);
}
您可以使用函数声明包装displayText
的调用,如下所示:
btn.onclick = function() {
displayText(myCustomText);
}
var myCustomText = "Hello World "; var myCustomText2 = "from Ele!"; document.querySelector('button').onclick = function() { displayText(myCustomText, myCustomText2); // Here you can pass the custom params. }; function displayText() { console.log(arguments); }
<button>Click me!</button>
采用函数addEventListener
绑定事件。
var myCustomText = "Hello World "; var myCustomText2 = "from Ele!"; document.querySelector('button').addEventListener('click', function() { displayText(myCustomText, myCustomText2); // Here you can pass the custom params. }); function displayText() { console.log(arguments); }
<button>Click me!</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.