简体   繁体   English

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

[英]dynamically added radio buttons onclick event not working?

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. 我正在尝试,1.从用户选择中使用Ajax获取响应,这使我将单选按钮属性的列表返回给我。2.获得属性列表后,我将使用createElement()创建单选按钮。3.然后附加该事件为onclick按钮的单选按钮。 4. Then i add element to the DOM using appedChild 4.然后我使用pedChild将元素添加到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 谢谢大家

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. 您可以通过两种方式将en元素动态添加到DOM:通过将html代码插入父元素或通过创建具有某些属性的子元素。 In your example the two methods are mixed - therefore senseless. 在您的示例中,这两种方法是混合的-因此没有意义。

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);

该属性称为onclick而不是onClick

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM