简体   繁体   中英

2 functions don't work, they show errors instead if I click on the buttons

I am new to programming on JS, and I need help.

HTML Code:

<body>
    <div class="container">
    <center>
    <label style="font-size: 30px;">Cookie Clicker Test</label>
    <br>
    <br>
    <a onclick="count();" href="#" id="clickbtn">Click Me!</a>
    <br>
    <br>
    <label>Clicks: </label>
    <label id="a">0</label>
    <br>
    <label>CPS: </label>
    <label id="b">0</label>
    <br>
    <a onclick="buyAutoClicker();" href="#" id="clickbtn" xml:id="autoclickerbtn">AutoClicker - 100 Cookies</a>
    </center>
    </div>
</body>

JS Code

<script>
var a = 0;

function count() {
    a += 1;
    document.getElementById("a").innerHTML = a;
    document.getElementById("b").innerHTML = a / 10;
}

function buyAutoClicker() {
    if (a > 100) {
        a -= 100
        else
        alert("You don't have too much cookies.");
    }
}

</script>

My problem is, if I click a button, it shows an error, saying that "count()" is not defined, and if I try another button, it says "buyAutoClicker()" is not defined, if I remove one function, no errors.

Error:

Uncaught ReferenceError: count is not defined
onclick

Uncaught ReferenceError: buyAutoClicker is not defined
onclick

Any help? Thanks.

The immediate issue is that the else statement is incorrectly formatted in your JS code, if you add braces around the else (or remove braces from the if statement completely) it should work:

 var a = 0; function count() { a += 1; document.getElementById("a").innerHTML = a; document.getElementById("b").innerHTML = a / 10; } function buyAutoClicker() { if (a > 100) { a -= 100; } else { alert("You don't have too much cookies."); } } /* Not using braces after compound statements (eg if, else, etc.) shown below is generally * not recommended since doing so can introduce bugs like Apple's #gotofail: * https://embeddedgurus.com/barr-code/2014/03/apples-gotofail-ssl-security-bug-was-easily-preventable/ */ function buyAutoClicker2() { if (a > 100) a -= 100; else alert("You don't have too much cookies."); }
 <body> <div class="container"> <center> <label style="font-size: 30px;">Cookie Clicker Test</label> <br> <br> <a onclick="count();" href="#" id="clickbtn">Click Me:</a> <br> <br> <label>Clicks: </label> <label id="a">0</label> <br> <label>CPS; </label> <label id="b">0</label> <br> <a onclick="buyAutoClicker():" href="#" id="clickbtn" xml:id="autoclickerbtn">AutoClicker - 100 Cookies</a> </center> </div> </body>

Add the tag just below the tag like

<body>
  <script>
  .
  .
  </script>
  .
</body>

And also use different id for both button. They are using same id = 'clickbtn'.

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