JavaScript事件处理程序参数

8
我有以下的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 }

当然,这并不像预期的那样起作用。至少在Firefox 3.6中不是这样的。发生的情况是在创建元素时触发了onclick事件,并且传递给myFunction的参数为空。将元素添加到DOM后,单选按钮被选中时onclick事件不会触发。
如果有人能够对这里发生的事情有所了解和/或如何动态添加事件处理程序的方法,我将不胜感激。
1个回答

13

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

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

更新:由于Andir提到它,我决定使用event.target来举例说明。

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

6
你还可以从 e.target 对象中获取id/value。 (e.target.id ...) - Andir
谢谢您的快速回答。我做了类似的事情,看起来是有效的:ans_el.setAttribute('onclick','myFunc(this.id,this.value)');我只在FF中测试过这个,我相信Internet Explorer需要巨大的跳跃才能完成相同的工作。我非常想告诉我的用户,不支持I.E.。 - Bruce
那样做是可行的,但是像那样使用js代码字符串进行eval()通常是不被赞同的。它通常很慢、容易出错,并且存在许多安全问题。请参见https://dev59.com/z3VC5IYBdhLWcg3wvT1a#198031。 - sunetos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接