动态添加的单选按钮onclick事件不工作?

时间:2023-01-04 20:19:50

I am trying following, 1. Get response using Ajax from the users selection which returns me the list of the radio buttons attributes as 2. Once i get the attribute list i am creating the radio buttons using createElement() 3. Then i am attaching the event to the radio button for onclick buttons. 4. Then i add element to the DOM using appedChild

我试着跟上,1。使用来自用户选择的Ajax获得响应,该选项将把单选按钮的列表属性作为2返回给我。一旦我获得了属性列表,我将使用createElement() 3创建单选按钮。然后我将这个事件附加到onclick按钮的单选按钮上。4所示。然后使用appedChild将元素添加到DOM中。

The below is code for adding radio button (for IE)

下面是添加单选按钮的代码(用于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/>';

Now in all this when i am adding the radio button to the DOM onclick is not working and i don't understand why ?

现在,当我将单选按钮添加到DOM onclick时,我不明白为什么?

Thanks all

感谢所有

2 个解决方案

#1


7  

You can dynamically add en element to the DOM by two ways: by inserting an html code into the parent element or by creating a child element with some properties. In your example the two methods are mixed - therefore senseless.

您可以通过两种方式动态地将en元素添加到DOM:通过将html代码插入父元素或通过创建具有某些属性的子元素。在你的例子中,这两种方法是混合的——因此毫无意义。

Method 1. Inserting HTML code:

方法1。插入HTML代码:

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

Method 2. Creating DOM child:

方法2。创建DOM孩子:

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

#2


0  

The property is called onclick not onClick

该属性称为onclick,而不是onclick。

#1


7  

You can dynamically add en element to the DOM by two ways: by inserting an html code into the parent element or by creating a child element with some properties. In your example the two methods are mixed - therefore senseless.

您可以通过两种方式动态地将en元素添加到DOM:通过将html代码插入父元素或通过创建具有某些属性的子元素。在你的例子中,这两种方法是混合的——因此毫无意义。

Method 1. Inserting HTML code:

方法1。插入HTML代码:

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

Method 2. Creating DOM child:

方法2。创建DOM孩子:

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

#2


0  

The property is called onclick not onClick

该属性称为onclick,而不是onclick。