[英]Vanilla Javascript : how to make a button clickable once only
I have a quiz app application that I am working on that dynamically creates 2-4 buttons for the answer.我有一个正在开发的测验应用程序,它会动态地为答案创建 2-4 个按钮。 However, if you click on an answer, you can keep clicking on the same answer or keep clicking the other answers.
但是,如果您单击一个答案,您可以继续单击相同的答案或继续单击其他答案。 I want the user to be able to click one of the buttons but then not be able to keep clicking.
我希望用户能够单击其中一个按钮,但随后无法继续单击。 caveat though: when a user clicks one of the buttons, a new "Next" button gets created and that one does still need it's click event.
但是需要注意的是:当用户单击其中一个按钮时,会创建一个新的“下一步”按钮,并且该按钮仍然需要它的单击事件。
tl;dr I need dynamically created buttons to be clickable only once but a "Next" button to still be clickable. tl;博士我需要动态创建的按钮只能点击一次,但“下一步”按钮仍然可以点击。
Code:代码:
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;
if you want to see what I'm talking about, the app can be found here: https://andrethetallguy.github.io/Animal-Quiz/如果你想看看我在说什么,可以在这里找到该应用程序: https://andrethetallguy.github.io/Animal-Quiz/
Thanks!!!谢谢!!!
In the handler function nextBtnFx you could disable the button with在处理程序 function nextBtnFx 中,您可以使用禁用按钮
this.disabled = "true"
that would make it unclickable after the first click这将使它在第一次点击后无法点击
ref : https://stackoverflow.com/a/17115132/13998159参考: https://stackoverflow.com/a/17115132/13998159
<.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>
You can use these functions to disable/enable the buttons.您可以使用这些功能来禁用/启用按钮。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.