【问题标题】:Adding onclick functions to buttons within JavaScript将 onclick 函数添加到 JavaScript 中的按钮
【发布时间】: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


    【解决方案1】:

    尽管在 JavaScript 中有很好的方法可以做到这一点。 但是,在这种情况下,自动运行 changeScore() 可以这样处理。

    responseOne.onclick = changeScore();
    

    用这个替换上面的行

    responseOne.onclick = changeScore;
    

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

    ?

    【讨论】:

      猜你喜欢
      • 2012-10-08
      • 2021-06-18
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      • 2011-10-20
      相关资源
      最近更新 更多