两个HTML按钮设置相同,但一个按钮不起作用

时间:2019-05-22 17:52:55

标签: javascript dom

我正在创建一个动态表单,用户可以在其中添加和删除按钮的输入,但是其中一个按钮确实具有onclick事件,而另一个按钮却没有设置,尽管它们的设置完全相同。

我尝试使用<button>并将函数更改为console.log,但是“添加答案选项”按钮从未收到onclick事件。

//add and remove buttons
        var addButton = document.createElement('input'); addButton.type = "button"
        var removeButton = document.createElement('input'); removeButton.type = "button"
        addButton.value = "Add Answer Option";
        removeButton.value = "Remove Answer Option";
        var buttonLi = document.createElement('li');
        buttonLi.innerHTML = "<br>"
        buttonLi.appendChild(addButton);
        buttonLi.innerHTML += ' ';
        buttonLi.appendChild(removeButton);

        var buttonUL = document.createElement('ul');
        this.mainElement.appendChild(buttonUL);

        buttonLi.style = "list-style-type: none;";
        buttonUL.appendChild(buttonLi);

        addButton.onclick = function() {quiz.questions[id].addAnswerOption();}
        removeButton.onclick = function() {quiz.questions[id].removeAnswerOption();}

JS小提琴:https://jsfiddle.net/bh7tsxqu/

“添加”按钮应添加一个答案选项,但不能。删除按钮应该删除答案选项,并且可以。

2 个答案:

答案 0 :(得分:0)

我只是给了按钮ID,并使用这些ID作为选择器来添加onclick事件。

具体地说,这就是我添加的内容。

Any

这就是我所做的修改。

contains

这是全部。

element

答案 1 :(得分:0)

您正在使用innerHtml属性添加内容。在按钮之间添加空格时,它将删除侦听器。要使代码正常工作,请删除以下行:

buttonLi.innerHTML += ' ';

并使用CSS在按钮之间添加空格。

或者您可以使用insertAdjacentHTML方法在按钮之间添加空格。

buttonLi.insertAdjacentHTML('beforeend',' ');

您可以在此处了解更多信息:innerHTML