最近中文字幕高清中文字幕无,亚洲欧美高清一区二区三区,一本色道无码道dvd在线观看 ,一个人看的www免费高清中文字幕

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用java腳本動態(tài)乘以2個單元格并在第三個單元格中顯示結(jié)果

使用java腳本動態(tài)乘以2個單元格并在第三個單元格中顯示結(jié)果

互換的青春 2024-01-22 20:45:45
我從數(shù)據(jù)庫中提取記錄,將它們顯示在帶有表單輸入字段的表行中。這意味著將會有多行,如下面的示例 html 代碼所示。我只想使用 JavaScript。這個想法是,當(dāng)用戶輸入數(shù)量時,它會乘以單價,結(jié)果顯示在小計(jì)字段中。我不是 JS 開發(fā)人員,我搜索并找到了下面的代碼,它接近我需要的代碼。如果有人可以提出一些建議以使該代碼正常工作,我將不勝感激。  <SCRIPT language="JavaScript"><!-- function calculate() {    var Quantity = document.getElementsByName("Quantity").value;    var unitPrice = document.getElementsByName("unitPrice").value;    var total = 0;    for (var i = 0; i < Quantity.length; i++) {            total += parseInt(Quantity[i].value) * parseInt(unitPrice[i]);    } document.getElementsByName("subtotal").value = total;} </SCRIPT> <table> <tr><td>  <input onblur="calculate()" name="Quantity" size="2" /> <input name="unitPrice" value="5" size="2"/><input name="subtotal" size="2"/>   </td>  </tr> <tr><td>  <input onblur="calculate()" name="Quantity" size="2" /> <input name="unitPrice" value="5" size="2"/><input name="subtotal" size="2"/>  </td>  </tr>  </table>
查看完整描述

1 回答

?
阿波羅的戰(zhàn)車

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個贊

有幾點(diǎn):a)document.getElementsByName("")返回一個 NodeList 元素集合,因此您無法像這樣獲取每個輸入的值,您必須在 for 循環(huán)內(nèi)獲取它們;b) 然后您還需要在解析之前獲取unitPrice[i]循環(huán)內(nèi)每個值的值,c) 每次迭代后應(yīng)重置總數(shù),因此可以將其放在循環(huán)內(nèi)。見下文:


function calculate() {

  var Quantity = document.getElementsByName("Quantity");

  var unitPrice = document.getElementsByName("unitPrice");

  for (var i = 0; i < Quantity.length; i++) {

    if (!Quantity[i].value) continue; // prevent NaN

    let total = parseInt(Quantity[i].value) * parseInt(unitPrice[i].value);

    document.getElementsByName("subtotal")[i].value = total;

  }

}

<table>

  <tr>

    <td>

      <input onblur="calculate()" name="Quantity" size="2" />

      <input name="unitPrice" value="5" size="2" />

      <input name="subtotal" size="2" />

    </td>

  </tr>


  <tr>

    <td>

      <input onblur="calculate()" name="Quantity" size="2" />

      <input name="unitPrice" value="5" size="2" />

      <input name="subtotal" size="2" />

    </td>

  </tr>

</table>

為了避免得到NaN沒有任何值的結(jié)果,您可以添加if (!Quantity[i].value) continue;為 for 循環(huán)中的第一行,這應(yīng)該可以防止它。



查看完整回答
反對 回復(fù) 2024-01-22
  • 1 回答
  • 0 關(guān)注
  • 200 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號