是输入信息后点击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>
在一个页面,没有操作怎么可以运算,我觉得你可以把结果的值写到下一个页面,然后用form表单提交一下,我不是很懂,同求解决办法。
优化一下
<html>
<head>
<script type='text/javascript'>
onload=compute;
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>