【问题标题】:Vanilla Javascript : how to make a button clickable once onlyVanilla Javascript:如何使按钮只能点击一次
【发布时间】:2020-07-30 16:53:26
【问题描述】:

我正在开发一个测验应用程序,它会动态创建 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/

谢谢!!!

【问题讨论】:

  • 在添加“下一步”按钮之前禁用按钮...

标签: javascript click


【解决方案1】:

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

this.disabled = "true" 

这将使它在第一次点击后无法点击

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

【讨论】:

  • 感谢您的回复,但这似乎并没有解决问题
【解决方案2】:

<!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>

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

【讨论】:

  • 感谢您的回复,但这不起作用:(
  • 你好,什么不能正常工作(你应该把启用/禁用功能放在你的代码中)我可以使用代码启用/禁用按钮(但你必须为你的按钮分配一个 ID首先使用它的方法。ID 分配:“" and in "document.getElementById("enter your ID here!") .disabled = false;"
  • 试过了还是可以点击多次
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多