2010-07-14 142 views
6

我有以下的JavaScript代码: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中。当元素被创建并且传递给myFunction的参数为空时,会触发事件onClick。将元素添加到DOM后,当单选按钮处于选中状态时,事件不会触发。

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

回答

11

您需要提供onclick函数的参考;您当前正在执行该功能并将该结果分配给onclick处理程序。这是更接近你想要什么:

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

更新:决定使用event.target更清晰的例子,因为Andir提出来的。

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

您还可以从e.target对象获取id/value。 (e.target.id ...) – Andir 2010-07-14 18:21:45

+0

感谢您的快速回答。我做了类似的工作: ans_el.setAttribute('onclick','myFunc(this.id,this.value)'); 我只在FF中测试过,我相信Internet Explorer需要惊人的跳跃才能完成相同的功能。我很想告诉我的用户I.E.将不被支持。 – Bruce 2010-07-14 18:23:49

+0

这会工作,但使用js代码字符串作为eval()这样的通常是皱眉。它通常很慢,很有问题,并且存在一些安全问题。见http://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil/198031#198031 – sunetos 2010-07-14 18:26:21