满足条件时更改显示

时间:2018-03-15 15:21:58

标签: javascript html css

我试图创建一个简单的倒计时按钮,当它达到0时显示一个段落。倒计时按钮有效,但段落不显示为0.我的代码如下。我有什么想法可能做错了吗?谢谢! 此外,我知道它不是最干净或最有效的代码,但我只是这样做来练习我的Javascript。



function countdown(){
  var currentVal = document.getElementById("countdown").innerHTML;
  var newValue = 0;
  if (currentVal > 0){
    newValue = currentVal - 1;
  }
  document.getElementById("countdown").innerHTML = newValue;
  if (currentVal = 0){
    var vacation = document.getElementById("vacation");
    vacation.style.display = "block";
  }
}

#vacation{
  display: none;
}

<h1>Days until vacation</h1>
<button id="countdown" onclick="countdown()">10</button>
<p id="vacation">Time for vacation woo!</p>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:3)

在javascript中,您应该使用===进行比较。 另外,我建议您将currentValue解析为整数,因为.innerHTML返回一个字符串。

所以用if (currentVal = 0){替换if (currentVal === 0){ 并使用var currentVal = parseInt(document.getElementById("countdown").innerHTML);,它应该工作!

&#13;
&#13;
function countdown(){
  var currentVal = parseInt(document.getElementById("countdown").innerHTML); // integer parsing
  var newValue = 0;
  if (currentVal > 0) {
    newValue = currentVal - 1;
  }
  document.getElementById("countdown").innerHTML = newValue;
  if (currentVal === 0){ // currentVal is equal to newValue (and they are both integers) so you can use either of them
    var vacation = document.getElementById("vacation");
    vacation.style.display = "block";
  }
}
&#13;
#vacation{
  display: none;
}
&#13;
<h1>Days until vacation</h1>
<button id="countdown" onclick="countdown()">10</button>
<p id="vacation">Time for vacation woo!</p>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

你写错了条件语句。有一个赋值而不是比较。因此,请更改为if (newValue === 0) {

答案 2 :(得分:0)

如果(currentVal === 0){。

,你写了一个错误的条件语句

答案 3 :(得分:0)

您正在使用赋值运算符而不是比较运算符来检查currentVal。请参阅更新的代码段:

&#13;
&#13;
function countdown(){
  var currentVal = document.getElementById("countdown").innerHTML;
  var newValue = 0;
  if (currentVal > 0){
    newValue = currentVal - 1;
  }
  document.getElementById("countdown").innerHTML = newValue;
  if (currentVal == 0){
    var vacation = document.getElementById("vacation");
    vacation.style.display = "block";
  }
}
&#13;
#vacation{
  display: none;
}
&#13;
<h1>Days until vacation</h1>
<button id="countdown" onclick="countdown()">10</button>
<p id="vacation">Time for vacation woo!</p>
&#13;
&#13;
&#13;