向 JavaScript 内的按钮添加 onclick 函数

Adding onclick functions to buttons within JavaScript

我正在尝试在 JavaScript 中进行测验。基本上我的代码有一个启动测验的按钮,当我单击它时,我删除了按钮并添加了四个。我为每个按钮添加了一个 onclick 属性。

responseOne.onclick = changeScore();

我希望这一行在我单击 'responseOne' 按钮时 运行 changeScore 函数。问题是当我 运行 函数 startQuiz()、函数 changeScore 运行s 四次时,甚至在删除和添加任何按钮之前。我的代码有什么问题?

此外,我真的很新,所以如果我的其他任何代码效率低下或其他问题,也总是欢迎建设性的批评:)

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 中有很好的方法可以做到这一点。 但是,在这种情况下,自动 运行 changeScore() 可以这样处理。

responseOne.onclick = changeScore();

用这个替换上面的行

responseOne.onclick = changeScore;

对所有 responseOne、responseTwo、responseThree 和 responseFour 执行此操作。