
写一段javascript(或jQuery)代码实现以下功能?
数量:<input type=”text”name=”count” value=””></input>
单价:<input type=”text” name=”price” value=”” ></input>
总价:<span name=”total” class=”total_cls” id=”total_id”></span>
1)、为数量与单价添加事件监听,当用户修改数量或单价时触发事件。
2)、写出js函数,能够计算总价格并将总价显示到span中。 展开
首先思路如下:
检测用户是否更改数量或单价
检测用户是否输入的是数字
计算,并返回值到总价中
简易代码如下:
以下为部分代码:
<!--onkeyup方法是在键盘按键按下并松开时发生-->
<body onkeyup="count(number.value,price.value)">
<input type="text" name="count" value="" id="number"></input>
<input type="text" name="price" value="" id="price"></input>
<span name="total" class="total_cls" id="total_id"></span>
<script>
//count()输入值是数量和价格的value
function count(n,p){
if(Number(n)==n & Number(p)==p)
//这一步是为了检测用户是否输入数字
{
document.getElementById("total_id").innerHTML=Number(n)*Number(p);
}
else
{
alert("输入有误");
}
}
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
数量:<input type="text" name="count" value=""></input>
单价:<input type="text" name="price" value="" ></input>
总价:<span name="total" class="total_cls" id="total_id"></span>
</body>
<script>
let numInput = document.querySelector("input[name=count]");
let priceInput = document.querySelector("input[name=price]")
let total = document.querySelector("#total_id")
numInput.oninput = ()=>{
total.innerHTML = numInput.value * priceInput.value
}
priceInput.oninput = ()=>{
total.innerHTML = numInput.value * priceInput.value
}
</script>
</html>
请采纳