-5

我有这个脚本,当用户从下拉列表中选择它们时,它会计算一些值的总和。我不是 JS 专家。除了 onchange 我希望这段代码来计算页面加载的值吗?我会假设它是此代码的一些复制和粘贴,对函数和 if 语句进行了更改?

<script>
$(function() {
     $(".DropChange").change(function(){
        var valone = $('#ValOne').val();
        var valtwo = $('#ValTwo').val();
        var valthree = $('#ValThree').val();
        var valfour = $('#ValFour').val();
        var valfive = $('#ValFive').val();
        var valsix = $('#ValSix').val();
        var valseven = $('#ValSeven').val();
        var valeight = $('#ValEight').val();
        var total = ((valone * 1) + (valtwo * 1) + (valthree * 1) + (valfour * 1) + (valfive * 1) + (valsix * 1) + (valseven * 1) + (valeight * 1));
        $('#Total').text(total);
    });
});
</script>
4

2 回答 2

1

可能您最简单的选择是将当前onchange函数粘贴到另一个函数中。

var calculateTotals = function(){    
    var valone = $('#ValOne').val();
    var valtwo = $('#ValTwo').val();
    var valthree = $('#ValThree').val();
    var valfour = $('#ValFour').val();
    var valfive = $('#ValFive').val();
    var valsix = $('#ValSix').val();
    var valseven = $('#ValSeven').val();
    var valeight = $('#ValEight').val();
    var total = ((valone * 1) + (valtwo * 1) + (valthree * 1) + (valfour * 1) + (valfive * 1) + (valsix * 1) + (valseven * 1) + (valeight * 1));
    $('#Total').text(total);
};

然后将您的更改onchange

$(".DropChange").change(calculateTotals);

所以你$(function(){ ... });现在的样子;

$(function(){
    $(".DropChange").change(calculateTotals); // assign event
    calculateTotals(); // calculate totals on load
});
于 2013-08-12T10:15:30.880 回答
0

这是您需要的:

<script>
(function() {
     $(document).ready(function(){
        showSum();
      });

      $(".DropChange").change(function(){
          showSum();
      }
      function showSum(){
            var valone = $('#ValOne').val();
            var valtwo = $('#ValTwo').val();
            var valthree = $('#ValThree').val();
            var valfour = $('#ValFour').val();
            var valfive = $('#ValFive').val();
            var valsix = $('#ValSix').val();
            var valseven = $('#ValSeven').val();
            var valeight = $('#ValEight').val();
            var total = ((valone * 1) + (valtwo * 1) + (valthree * 1) + (valfour * 1) + (valfive * 1) + (valsix * 1) + (valseven * 1) + (valeight * 1));
        $('#Total').text(total);
      }
}());
</script>
于 2013-08-12T10:19:22.373 回答