是輸入信息後點擊input外邊的范圍才會運算,但是目前已經有信息,如何省卻上述步驟直接運算?
<html>
<head>
<script>
function compute()
{
var a,b;
if(document.getElementById("txt1").value!="" && document.getElementById("txt2").value!="")
{
a=parseFloat(document.getElementById("txt1").value);
b=parseFloat(document.getElementById("txt2").value);
document.getElementById("txt3").value=(a/b).toFixed(2);
}
}
</script>
</head>
<body>
<input onchange="compute()" value="123123" id="txt1">
<input onchange="compute()" value="123123" id="txt2">
<input id="txt3" readonly>
</body>
</html>
兩個地方改一下,把onchange改成oninput,另外加一個onload事件,初始化txt3的值,這樣就可以同時滿足:初始值和自動運算,請看demo
<html>
<head>
<script type='text/javascript'>
onload=function(){
var a=parseFloat(document.getElementById("txt1").value),
b=parseFloat(document.getElementById("txt2").value);
document.getElementById("txt3").value=(a/b).toFixed(2);
}
function compute(){
a=parseFloat(document.getElementById("txt1").value);
b=parseFloat(document.getElementById("txt2").value);
if(a!="" && b!=""){
document.getElementById("txt3").value=(a/b).toFixed(2);
}
}
</script>
</head>
<body>
<input oninput="compute()" value="123123" id="txt1">
<input oninput="compute()" value="123123" id="txt2">
<input id="txt3" readonly>
</body>
</html>