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后,当单选按钮处于选中状态时,事件不会触发。
如果有人对这里发生的事情有一些了解,并且/或者如何动态添加事件处理程序,我将不胜感激。
您还可以从e.target对象获取id/value。 (e.target.id ...) – Andir 2010-07-14 18:21:45
感谢您的快速回答。我做了类似的工作: ans_el.setAttribute('onclick','myFunc(this.id,this.value)'); 我只在FF中测试过,我相信Internet Explorer需要惊人的跳跃才能完成相同的功能。我很想告诉我的用户I.E.将不被支持。 – Bruce 2010-07-14 18:23:49
这会工作,但使用js代码字符串作为eval()这样的通常是皱眉。它通常很慢,很有问题,并且存在一些安全问题。见http://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil/198031#198031 – sunetos 2010-07-14 18:26:21