计数的增减

Increase and Decrease of count

我正在尝试创建一个可以通过单击按钮来增加和减少的代码 html 代码,但问题是我无法让它运行我尝试了不同的选项。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="styles.css">
    <title>Document</title>
</head>

<body>
    <div id="body">
        <h1>COUNTER</h1>
        <span id="time">0</span><br>
        <button id="lower"  onclick="reduceone()" type="button">LOWER COUNT</button><BR>
        <button id="add" onclick="addone()" type="button">ADD COUNT</button>
    </div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="index.js"></script>
</body>
</html>

javascript代码:

$("#add").click(function (){
    let count = 0;
    count ++;
    $("#time").text(count);
});

$(#lower).click(function(){
    let count = 0;
    count --;
    $("#time").text(count)
});

试试这个

   let count = 0;
$("#add").click(function (){
    count ++;
    $("#time").text(count);
});

$(#lower).click(function(){
    count --;
    $("#time").text(count)
});

您必须使变量 (count) 成为全局变量,以便所有函数都可以访问他的值。如果你把 variable(count) 放在一个函数中,那么只有那个函数可以访问他的值。希望你明白

您需要在两个函数之间共享状态,这样每个函数都可以看到它们正在更改的共享状态。

此外,所有 id 或 class 名称都应该像这样在引号之间 "#lower"

let count = 0; // Shared state that both functions can see

$("#add").click(function (){
    count++;
    $("#time").text(count);
});

$("#lower").click(function(){ // "#lower" not #lower
    count--;
    $("#time").text(count)
});