2014-03-31 40 views
0

Here是小提琴。添加按鈕行爲怪異

問題是添加按鈕不會第一次響應。第二次,它會創建兩個,第三個三個,第四個四個等等,而不是創建一個單選按鈕。

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(); 
       } 
      } 
     ); 
    }); 
} 
+0

我點擊顯示,每次創建一個。最新的FF在mac – Huangism

+0

嗨@Huangism ....它的'添加'按鈕功能奇怪不是'顯示'按鈕。點擊'Show'後開始點擊'Add'按鈕。 – envyM6

+0

問題是你每次點擊都調用radio()。你需要檢查是否已經有一個監聽器,並且如果有監聽器沒有添加新監聽器。 – Seiyria

回答

0

你的HTML有按鈕的onclick屬性,但隨後的處理程序中,您添加更多處理器!您不應該在radio函數內調用addEventListener。每次點擊時,它都會添加另一個處理程序,因此下一次點擊會使其再次執行一次。

http://jsfiddle.net/KcLj6/5/

更新修復刪除按鈕。

有一個更新的小提琴,我已經重新安排了一下代碼。您需要選擇將回調置於onclick或使用addEventListener,而不是兩者。

+0

只是完美!!!! @Tesserex ....非常感謝:) – envyM6

+0

但嘿,但現在'刪除'按鈕不工作:( – envyM6

+0

嗨@Tesserex嗨刪除按鈕是現在不能正常工作了......你能幫我調試嗎? – envyM6