JavaScript 事件处理程序参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3249128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:52:54  来源:igfitidea点击:

JavaScript event handler arguments

javascriptjavascript-events

提问by Bruce

I have the following JavaScript code:

我有以下 JavaScript 代码:

var ans_el = document.createElement( 'input' );
ans_el.setAttribute( 'id', unique_int_value );
ans_el.setAttribute( 'type', 'radio' );
ans_el.setAttribute( 'name', 'group' );
ans_el.setAttribute( 'value', 'myValue' );
ans_el.onclick = myFunction( this.id, this.value ); 

// Add ans_el to DOM.

function myFunction( index, value ) { // do something }

This, of course, does not work as expected. At least not in Firefox 3.6. What happens is the onclickevent is fired when the element is created and the arguments passed to myFunctionare null. After the element is added to the DOM, the onclickevent does not fire when the radio button is select.

当然,这不会按预期工作。至少在 Firefox 3.6 中不是。发生的情况是在创建元素并且传递给myFunction的参数为空时触发onclick事件。将元素添加到 DOM 后,选择单选按钮时不会触发onclick事件。

I'd be grateful if anyone has some insight into what's happening here, and/or how dynamically adding event handlers can be accomplished.

如果有人对这里发生的事情和/或如何动态添加事件处理程序有一些了解,我将不胜感激。

回答by sunetos

You need to give a reference to a function for onclick; you are currently executing the function and assigning that result to the onclick handler. This is closer to what you want:

您需要为 onclick 提供一个函数的引用;您当前正在执行该函数并将该结果分配给 onclick 处理程序。这更接近你想要的:

ans_el.onclick = function(e) {
   myFunction(ans_el.id, ans_el.value);
};

UPDATED: Decided to use event.target for a clearer example since Andir brought it up.

更新:决定使用 event.target 作为一个更清晰的例子,因为 Andir 提出了它。

ans_el.onclick = function(e) {
   myFunction(e.target.id, e.target.value);
};