我有这个脚本,当用户从下拉列表中选择它们时,会计算一些值的总和。我不是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>
答案 0 :(得分: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
});
答案 1 :(得分: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>