我正在创建一个简单的任务,在用户单击按钮3次后,文本会显示出来。但是,该代码似乎没有按我预期的那样工作。
我尝试在MDN guide中概述的if语句中添加双括号,但没有运气,还检查了one这样的Stack Overflow中类似的问题,但是它们使用的是jquery,所以我不知道它是如何工作的。
这是我的代码:
function countDown() {
var currentval = document.getElementById("countDownBtn").innerHTML;
var newval = currentval - 0;
if (currentval > 0) {
newval = currentval - 1;
}
document.getElementById("countDownBtn").innerHTML = newval;
}
if (currentval = 0) {
document.getElementById("newText").innerHTML = "You clicked 3 times!;
}
<button id="countDownBtn" onclick="countDown()">3</button>
<p id="newText"></p>
我确定我在这里错过了重要的事情,感谢您的指导。
答案 0 :(得分:3)
if (currentval = 0) {
应该为if (currentval == 0) {
,并且您的if
条件不在countDown()
函数之外。
function countDown() {
var currentval = document.getElementById("countDownBtn").innerHTML;
console.log(currentval);
var newval = currentval - 0;
if (currentval > 0) {
newval = currentval - 1;
}
document.getElementById("countDownBtn").innerHTML = newval;
if (currentval == 0) {
document.getElementById("newText").innerHTML = "You clicked 3 times!";
}
}
<button id="countDownBtn" onclick="countDown()">3</button>
<p id="newText"></p>
答案 1 :(得分:1)
您所犯的错误已经被提及,我只是想添加一个更简洁的代码来回答。您确实不应该使用onclick
之类的内联事件侦听器,而应使用HTMLElement.prototype.addEventListener
:
countDownBtn.addEventListener('click', () => {
if (Number(countDownBtn.textContent)) {
countDownBtn.textContent -= 1;
}
if (!Number(countDownBtn.textContent)) {
countDownBtn.disabled = true;
newText.textContent = "You clicked 3 times!";
}
})
<button id="countDownBtn">3</button>
<p id="newText"></p>
答案 2 :(得分:0)
count = 0
function countDown() {
var currentval = document.getElementById("countDownBtn").innerHTML;
if (count < 3) {
count = count+1
}else{
alert("hi")
}
}
<button id="countDownBtn" onclick="countDown()">3</button>
<p id="newText"></p>
答案 3 :(得分:0)
您错过了“ =“ =” (currentval == 0)
function countDown() {
var currentval = document.getElementById("countDownBtn").innerHTML;
var newval = currentval - 0;
if (currentval > 0) {
newval = currentval - 1;
}
document.getElementById("countDownBtn").innerHTML = newval;
if (currentval == 0) {
document.getElementById("newText").innerHTML = "You clicked 3 times!;"
}
}
<button id="countDownBtn" onclick="countDown()">3</button>
<p id="newText"></p>
答案 4 :(得分:0)
除了上面的答案外,更简洁的代码是:
countDownBtn.addEventListener('click', (e) => {
if (Number(e.target.innerHTML)) {
e.target.innerHTML -= 1;
}else{
e.target.disabled = true;
newText.textContent = "You clicked 3 times!";
}
})
<button id="countDownBtn">3</button>
<p id="newText"></p>