問題是添加按鈕不會第一次響應。第二次,它會創建兩個,第三個三個,第四個四個等等,而不是創建一個單選按鈕。
function RadioButtonContent()
{
var rbc = '<h3>Type your radio button here:</h3><input type="text" name="option" id="option" value="Example 1" /><button id="AddButton" onclick="radio()">Add</button><button id="RemoveButton">Remove</button><div id="updateDivRadio"><h1>Space for Radio Button</h1></div>';
var rbcAppen = document.getElementById('radioButton');
var newNode = document.createElement("div");
newNode.innerHTML = rbc;
rbcAppen.appendChild(newNode);
}
function radio()
{
function createRadioElement(elem, label, checked) {
var id = 'option1_' + label;
var div = document.createElement('div');
div.innerHTML = '<input type="radio" name="option1" id="' + id + '" value="1" /><label for="' + id + '">' + label + '</label>';
document.getElementById('updateDivRadio').appendChild(div);
}
document.getElementById('AddButton').addEventListener('click', function() {
var x = document.getElementById('option').value;
createRadioElement(this, x);
});
document.getElementById('RemoveButton').addEventListener('click', function() {
[].forEach.call(document.getElementById('updateDivRadio').querySelectorAll("input"),
function (el) {
if (el.checked) {
el.parentNode.remove();
}
}
);
});
}
我點擊顯示,每次創建一個。最新的FF在mac – Huangism
嗨@Huangism ....它的'添加'按鈕功能奇怪不是'顯示'按鈕。點擊'Show'後開始點擊'Add'按鈕。 – envyM6
問題是你每次點擊都調用radio()。你需要檢查是否已經有一個監聽器,並且如果有監聽器沒有添加新監聽器。 – Seiyria