【发布时间】:2021-07-13 00:51:49
【问题描述】:
我正在尝试用 JavaScript 进行测验。基本上我的代码有一个开始测验的按钮,当我点击它时,我删除了这个按钮并添加了四个。我为每个按钮添加了一个 onclick 属性。
responseOne.onclick = changeScore();
当我点击“responseOne”按钮时,我希望这条线能够运行changeScore 函数。问题是当我运行函数startQuiz() 时,函数changeScore 运行了四次,然后才删除和添加任何按钮。我的代码有什么问题?
而且我真的很新,所以如果我的任何其他代码效率低下或其他什么,建设性的批评也总是受欢迎的:)
function startQuiz() {
//remove the start quiz button
var element = document.getElementById("dummy")
element.parentNode.removeChild(element);
//change the h1 and h2 html tags to the question number and question
h1.innerHTML = title[questionNumber];
h2.innerHTML = questions[questionNumber];
//create buttons and give them bootstrap and onclick functions, appending them to empty divs
var responseOne = document.createElement("button");
responseOne.innerHTML = responseA[questionNumber];
responseOne.onclick = changeScore();
responseOne.classList.add("btn");
responseOne.classList.add("btn-primary");
document.getElementById("button1").appendChild(responseOne);
var responseTwo = document.createElement("button");
responseTwo.innerHTML = responseB[questionNumber];
responseTwo.onclick = changeScore();
responseTwo.classList.add("btn");
responseTwo.classList.add("btn-danger");
document.getElementById("button2").appendChild(responseTwo);
var responseThree = document.createElement("button");
responseThree.innerHTML = responseC[questionNumber];
responseThree.onclick = changeScore();
responseThree.classList.add("btn");
responseThree.classList.add("btn-warning");
document.getElementById("button3").appendChild(responseThree);
var responseFour = document.createElement("button");
responseFour.innerHTML = responseD[questionNumber];
responseFour.onclick = changeScore();
responseFour.classList.add("btn");
responseFour.classList.add("btn-success");
document.getElementById("button4").appendChild(responseFour);
}
function changeScore() {
alert("changeScore function is running");
}
【问题讨论】:
标签: javascript function button onclick