簡體   English   中英

JavaScript事件處理程序參數

[英]JavaScript event handler arguments

我有以下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的參數為null時,會觸發onclick事件。 將元素添加到DOM后,選擇單選按鈕時不會觸發onclick事件。

如果有人對這里發生的事情有所了解,和/或如何動態添加事件處理程序,我將不勝感激。

你需要為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);
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM