简体   繁体   English

添加按钮的行为很奇怪

[英]Add button acts weird

Here is the fiddle. 是小提琴。

The problem is Add button doesn't respond first time. 问题是“添加”按钮第一次没有响应。 Second time it does and then instead of creating one radio button it creates two, third time three, fourth time four and so on. 第二次执行此操作,然后而不是创建一个单选按钮,而是创建了两个,第三次是三个,第四次是四个,依此类推。

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

Your HTML has an onclick attribute for the buttons, but then inside the handler, you add more handlers! 您的HTML具有按钮的onclick属性,但是在处理程序内部,您添加了更多处理程序! You shouldn't have the addEventListener calls inside the radio function. 您不应该在radio函数中使用addEventListener调用。 Each time you click, it's adding another handler, so the next click makes it do it an additional time. 每次单击时,它都会添加另一个处理程序,因此,下次单击时,它会额外执行一次。

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

Updated to fix remove button. 更新以修复删除按钮。

There is an updated fiddle where I've rearranged the code a bit. 有更新的小提琴,在这里我对代码进行了一些重新排列。 You need to choose to either put the callback in onclick , or use addEventListener , not both. 您需要选择将回调置于onclick ,或使用addEventListener ,而不要同时使用两者。

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

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