2010-03-19 166 views
2

我正在嘗試, 1.使用Ajax從用戶選擇中獲得響應,它將單選按鈕屬性的列表返回爲 2.一旦我得到屬性列表,我將使用createElement()創建單選按鈕() 3然後我將事件附加到onclick按鈕的單選按鈕上。 4.然後,添加元素使用appedChild動態添加單選按鈕onclick事件不起作用?

的DOM的下面是對該所有加入的單選按鈕(用於IE)

var radio = '<input '; 
radio += 'type ="radio" '; 
radio += 'id="' + id + '" '; 
radio += 'value="" '; 
radio += '/>'; 
radioButton = document.createElement(radio); 
radioButton.onClick = function(){alert('this is test')} 
ele.appendChild(radioButton); 
ele.innerHTML += 'none' + '<br/>'; 

現在,當我加入的單選按鈕的DOM代碼的onclick不工作,我不明白爲什麼?

感謝所有

回答

7

您可以連接元素通過兩種方式動態地添加到DOM:通過插入HTML代碼插入到父元素或創建一個子元素一些屬性。在你的例子中,兩種方法是混合的 - 因此毫無意義。

方法1.插入HTML代碼:

var radio = '<input type ="radio" id="' + id + '" value="" />'; 
ele.innerHTML = radio; 
document.getElementById(id).onclick = function(){ alert('this is test'); }; 

方法2.創建DOM孩子:

var radioButton = document.createElement('input'); 
radioButton.type = "radio"; 
radioButton.id = id; 
radioButton.onclick = function(){ alert('this is test'); }; 
ele.appendChild(radioButton); 
0

該屬性稱爲onclickonClick