帮我精简并改进一串javascript代码,有点麻烦。

来源:百度知道 编辑:UC知道 时间:2024/05/24 03:46:59
<script type="text/javascript">
function showprice(sclass,money,classname){
document.getElementById("showprice_"+sclass).innerText=money;
document.getElementById("showprice_n"+sclass).innerText=classname;
document.getElementById("showprice_sum").innerText=parseInt(document.getElementById("showprice_1").innerText)+parseInt(document.getElementById("showprice_2").innerText)+parseInt(document.getElementById("showprice_3").innerText);
}
</script>
</head>
<body>
<input type="button" id="showprice1" onclick="showprice(1,2000,'一班')" value="一班" />
<input type="button" id="showprice2" onclick="showprice(2,2500,'二班')" value="二班" />
<input type="button" id="showprice3" onclick="showprice(3,2600,'三班')&q

你这个没有重复的语句,无需使用循环。

如果有数十个班,那么下面这个语句可以考虑用循环简化:
document.getElementById("showprice_sum").innerText=parseInt(document.getElementById("showprice_1").innerText)+parseInt(document.getElementById("showprice_2").innerText)+parseInt(document.getElementById("showprice_3").innerText);
简化的循环语句为下面一段:
var v_sum=0;
for (var i=1;i<=3;i++) v_sum+=parseInt(document.getElementById("showprice_"+i).innerText);
document.getElementById("showprice_sum").innerText=v_sum;