简体   繁体   English

如何在第一次加载页面时运行 Javascript 代码?

[英]How do I run a Javascript code at the first time of loading the page?

I have a JS function to calculate given data multiply by another input data.我有一个 JS 函数来计算给定数据乘以另一个输入数据。

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;
}

and my HTML和我的 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>

This code is working but at the beginning of the page this span is showing nothing.此代码正在运行,但在页面开头此跨度未显示任何内容。 But I already added value 1 to each input.但是我已经为每个输入添加了值 1。 How I get an initial subtotal at the beginning???我如何在开始时获得初始小计???

i think this is what u are expecting please tell me if it is wrong.我认为这就是你所期待的,如果它是错误的,请告诉我。

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>

Try this.尝试这个。 We set the function total to be called when the page loads.我们设置了在页面加载时调用的函数total It's also good practice to set the event handlers for onkeyup in the JS rather than HTML.在 JS 而不是 HTML 中为onkeyup设置事件处理程序也是一种很好的做法。 This is to separate the layout and the behavior of the website, so I've done that as well.这是为了将网站的布局和行为分开,所以我也这样做了。

HTML 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 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/ https://jsfiddle.net/y5pgrcc4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM