Vanilla Javascript:如何仅使按钮可单击一次

时间:2020-07-27 19:21:02

标签: javascript click

我有一个正在处理的测验应用程序,可以动态创建2-4个答案按钮。但是,如果您单击一个答案,则可以继续单击相同的答案,也可以继续单击其他答案。我希望用户能够单击其中一个按钮,但随后又不能继续单击。但需要注意的是:当用户单击其中一个按钮时,会创建一个新的“下一步”按钮,并且该按钮仍然需要单击事件。

tl;博士 我需要动态创建的按钮只能被单击一次,而“下一步”按钮仍可以被单击。

代码:

function renderButtons() {
  var answerContainer = document.getElementById("answer-buttons");
  answerContainer.innerHTML = "";

  for (var i = 0; i < 4; i++) {
    var button = document.createElement("button");
    button.classList.add("btn");
    button.setAttribute("id", "answerBtns");
    button.hasAttribute("data-correct");
    button.setAttribute("data-correct", questions[count].answers[i].correct);
    button.onclick = btnclick;
    button.textContent = questions[count].answers[i].text;
    answerContainer.appendChild(button);
  }
}

// if user clicks on button check if true
function btnclick(e) {
  e.preventDefault();
  var value = event.target.dataset.correct;
  scoreBox.textContent = "Score: " + score;
  if (value === "true") {
    score += 5;
    document.body.style.background = "green";
  } else {
    document.body.style.background = "red";
  }

  var next = document.getElementById("answer-buttons");
  var nextBtn = document.createElement("button");
  nextBtn.classList.add("nextBtn");
  nextBtn.textContent = "Next";

  next.appendChild(nextBtn);

  nextBtn.onclick = nextBtnFx;

如果您想了解我在说什么,可以在以下位置找到该应用程序: https://andrethetallguy.github.io/Animal-Quiz/

谢谢!

2 个答案:

答案 0 :(得分:1)

在处理程序函数nextBtnFx中,您可以使用禁用按钮

this.disabled = "true" 

第一次点击后将使其无法点击

参考https://stackoverflow.com/a/17115132/13998159

答案 1 :(得分:0)

<!DOCTYPE html>
<html>

<head>
  <title>Button</title>
</head>

<body>
  <input type="button" id="btn01" value="OK">

  <button onclick="disableElement()">Disable</button>
  <button onclick="enableElement()">Enable</button>
  <script>
    function disableElement() {
      document.getElementById("btn01").disabled = true;
    }

    function enableElement() {
      document.getElementById("btn01").disabled = false;
    }
  </script>

</body>

</html>

您可以使用这些功能来禁用/启用按钮。