2010-07-14 140 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