2016-07-10 128 views
-2

我有一个JS函数来计算给定的数据乘以另一个输入数据。如何在第一次加载页面时运行Javascript代码?

var item1unitp = 150; 
var item2unitp = 320; 

function total() { 

    var x1 = document.getElementById('t1').value; 
    var x1p = parseInt(x1); 
    var tot1 = item1unitp * x1p; 

    var x2 = document.getElementById('t2').value; 
    var x2p = parseInt(x2); 
    var tot2 = item2unitp * x2p; 

    var tot = tot1+tot2; 

    document.getElementById('tot').innerHTML = tot; 
} 

和我的HTML

Item 1 : <input type="text" id="t1" value="1" onkeyup="total();"/> <br/><br/> 

Item 2 : <input type="text" id="t2" value="1" onkeyup="total();"/> <br/><br/> 

Sub Total : <span id="tot"></span> 

此代码工作,但在页面开始这个跨度深藏不露。但是我已经为每个输入添加了值1。我如何在开始时获得初始小计?

+3

您运行的功能,只需添加'总()'某处** **后在DOM – adeneo

+0

的元素可以你更具体?? –

+1

把它放在''标签之前的最简单的方法:'' –

回答

1

我认为这是你期待的,请告诉我,如果它是错误的。

Sub Total : <span id="tot" value="total()"></span> 
<script> 
var item1unitp = 150; 
var item2unitp = 320; 

function total() { 

    var x1 = document.getElementById('t1').value; 
    var x1p = parseInt(x1); 
    var tot1 = item1unitp * x1p; 
    var x2 = document.getElementById('t2').value; 
    var x2p = parseInt(x2); 
    var tot2 = item2unitp * x2p; 
    var tot = tot1+tot2; 

    document.getElementById('tot').innerHTML = tot; 
    return tot; 
} 
total(); 
</script> 
1

试试这个。我们设置功能total在页面加载时被调用。在JS中而不是HTML中设置onkeyup的事件处理程序也是很好的做法。这是为了分离网站的布局和行为,所以我也这样做了。

HTML

Item 1 : <input type="text" id="t1" value="1" /> <br/> <br/> 
Item 2 : <input type="text" id="t2" value="1" /> <br/> <br/> 
Sub Total : <span id="tot"></span> 

JS

var item1unitp = 150; 
var item2unitp = 320; 

t1.onkeyup = total; 
t2.onkeyup = total; 
window.onload = total; 

function total(){ 

    var x1 = document.getElementById('t1').value; 
    var x1p = parseInt(x1); 
    var tot1 = item1unitp * x1p; 

    var x2 = document.getElementById('t2').value; 
    var x2p = parseInt(x2); 
    var tot2 = item2unitp * x2p; 

    var tot = tot1+tot2; 

    document.getElementById('tot').innerHTML = tot; 
} 

https://jsfiddle.net/y5pgrcc4/

相关问题