简体   繁体   中英

How to assign the value of 0 to a variable?

Javascript function 1:

var count = 0;

function myFunction()
{
count++;
document.getElementById("count").innerHTML=count;
}

Javascript function 2:

function demo() {
var y=document.getElementById("count").innerHTML;
if(y=="0") {
alert("There's nothing to be reset.");
}
else {
var count=0;
alert("Reset.");
// alternative code I used: document.getElementById("count").innerHTML="0";
}
}

HTML code:

<a href="Javascript:myFunction()">Click here</a>
<p>Total:<span id="count">0</span></p>
<button onclick="demo()">reset</button>

Is there a way to reset the variable to 0 in this code?

I've tried to reset the variable count to zero using document.getElementById() and adding =0; to the variable. Neither of these work. For example, if the user was to click the link the count would increase to 1. When they click the reset button it would appear to reset to 0 (unless using `var count=0;). However, if the user were to click the link again the count would be return the value 2, as it could simply continue to increment from the previous time.

I'm sorry if this has already been answered somewhere else, but it's very difficult to search for the terms = and ++ .

You made it a local variable by using var

else {
    var count=0;
    alert("Reset.");

should be

else {
    count=0;
    alert("Reset.");

Two things:

  1. Get rid of var where you reset the variable. That's giving you a separate local variable with the same name.

  2. Using "count" as a variable name, if it's global, will cause problems if you've also got an element whose id is "count" in the DOM. Use a different variable name or a different id, or make sure that the variable is not global (can't tell from posted code).

The things you need to chnage in the code are:

And make the comparison to

   if(parseInt(y) === 0) // You are converting it to integer and doing a strict check

the else construct to

  else {
    count = 0;
    alert('Reset');
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM