<head>
<script>
function cal() {
var appleVolum = Number(document.getElementById("appleVolum").value)
var bananaVolum = Number(document.getElementById("bananaVolum").value)
var pineappleVolum = Number(document.getElementById("pineappleVolum").value)
document.getElementById("msg").value = "共花费:" + (appleVolum * 10 + bananaVolum * 20 + pineappleVolum * 20)
}
</script>
</head>
<body>
苹果每斤10元,请输入您要购买的斤数:<input id="appleVolum"><br>
香蕉每斤20元,请输入您要购买的斤数:<input id="bananaVolum"><br>
菠萝每斤20元,请输入您要购买的斤数:<input id="pineappleVolum"><button onclick="cal()">我买</button><br>
信息:<input id="msg">
</body>
</html>
新建一个记事本,把以下代码拷贝进去,保存成.html文件就可以运行了代码如下:
<html>
<head><title>单价数量求和</title></head>
<body>
<table align="center" border="1" width="650">
<tr><td align="center" colspan="4"><b>订单</b></td></tr>
<tr>
<td align="center" width="50"><b>名称</b></td>
<td align="center" width="200"><b>单价</b></td>
<td align="center" width="200"><b>数量</b></td>
<td align="center" width="200">
<input type="button" value="总价" onclick="pay()" />
</td>
</tr>
<tr>
<td align="center">U盘</td>
<td align="center"><input id="objectPrice" type="text" width="195" /></td>
<td align="center"><input id="objectNum" type="text" width="195" /></td>
<td align="center"><input id="objectPay" type="text" width="195" readOnly="true" /></td>
</tr>
</table>
<script type="text/javascript">
function pay() {
var resultPrice = document.getElementById("objectPrice").value
var resultNum = document.getElementById("objectNum").value
if(resultPrice == "") {
alert("物品单价不能为空!")
document.getElementById("objectPay").value = ""
return false
}
if(isNaN(resultPrice) || resultPrice <0) {
alert("非法的商品单价!")
document.getElementById("objectPay").value = ""
return false
}
if(resultNum == "") {
alert("物品数量不能为空!")
document.getElementById("objectPay").value = ""
return false
}
if(!checkNum(resultNum)) {
alert("非法的商品数量!")
document.getElementById("objectPay").value = ""
return false
}
var resultPay = parseFloat(resultPrice)*parseInt(resultNum)
document.getElementById("objectPay").value = resultPay
}
function checkNum(num) {
var re = /^\d+$/
return re.exec(num) != null
}
</script>
</body>
</html>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)