簡體   English   中英

如何在第一次加載頁面時運行 Javascript 代碼?

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

我有一個 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;
}

和我的 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。 我如何在開始時獲得初始小計???

我認為這就是你所期待的,如果它是錯誤的,請告訴我。

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>

嘗試這個。 我們設置了在頁面加載時調用的函數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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM