在jQuery中向变量添加值的问题

Beh*_*ini 2 javascript jquery

你能看一下这个Demo,让我知道为什么我无法var result在代码中为变量添加值吗?我想我在全局范围内声明了结果,所以所有方法都可以访问它,但它对我来说不起作用!

这是我的代码:

<ul>
    <li><input type="checkbox" id="25" />25</li>
    <li><input type="checkbox" id="50" />50</li>
    <li><input type="checkbox" id="75" />75</li>
</ul>
<div id="result"></div>
Run Code Online (Sandbox Code Playgroud)

和jQuery代码:

$(document).ready(function () {
    var result = 0;
    $("#25").on("click", function () {
        var newResult = result + 25;
        $("#result").html(newResult);
    });
    $("#50").on("click", function () {
        var newResult = result + 50;
        $("#result").html(newResult);
    });
    $("#75").on("click", function () {
        var newResult = result + 75;
        $("#result").html(newResult);
    });
});
Run Code Online (Sandbox Code Playgroud)

谢谢.

Aru*_*hny 5

  • 第一个jQuery没有添加到小提琴中
  • 选择项目时,不会更新结果的值

尝试

$(document).ready(function () {
    var result = 0;
    $("#25, #50, #75").on("change", function () {
        if (this.checked) {
            result += +this.id;
        } else {
            result -= +this.id;
        }
        $("#result").html(result);
    });
});
Run Code Online (Sandbox Code Playgroud)

演示:小提琴