簡體   English   中英

Javascript 將 div A 的內容與 div B 的內容相乘並顯示在 div C 中(在更改 div A 時觸發)

[英]Javascript times the contents of div A with div B and display in div C (triggered when div A is changed)

我需要的是監聽 div "qty_a-row" 的變化,然后將 div "qty_a-row" 的值與 div "price-a-row" 的值相乘,並將答案放在 div "sub-total-一排”

這是我嘗試過的..

<div id="qty-a-row" contenteditable='true'></div><br>
<div id="price-a-row" contenteditable='true'></div><br>
<div id="sub-total-a-row" contenteditable='true'></div>
var contents = $(".qty-a-row").html();
$(".qty-a-row").blur(function () {
  if (contents != $(this).html()) {
    var x = parseInt(document.getElementById("qty-a-row").value);
    var y = parseInt(document.getElementById("price-a-row").value);
    document.getElementById("sub-total-a-row").innerText = (x * y);
  }
});

為了測試,我在 div“price-a-row”中輸入一個值,然后輸入一個數量,結果應該顯示,但現在顯示。

JSF 添加了https://jsfiddle.net/eLgrmbuj/

您正在使用 jQuery,但您沒有將其包含在頁面中,這就是您收到ReferenceError: $ is not defined
您正在使用類選擇器為 blur 事件選擇 div . 用於類#用於 id
Div 沒有value屬性,您必須使用textContent來獲取數字

 var contents = $("#qty-a-row").html(); $("#qty-a-row").blur(function () { if (contents != $(this).html()) { var x = parseInt(document.getElementById("qty-a-row").textContent); var y = parseInt(document.getElementById("price-a-row").textContent); document.getElementById("sub-total-a-row").textContent = (x * y); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="qty-a-row" contenteditable='true'>2</div><br> <div id="price-a-row" contenteditable='true'>1.00</div><br> <div id="sub-total-a-row" contenteditable='true'></div>


有關沒有 jQuery 的版本,請參見下文

 var contents = document.getElementById("qty-a-row").innerHTML; document.getElementById("qty-a-row").addEventListener('blur', function () { if (contents != this.innerHTML) { var x = parseInt(document.getElementById("qty-a-row").textContent); var y = parseInt(document.getElementById("price-a-row").textContent); document.getElementById("sub-total-a-row").textContent = (x * y); } });
 <div id="qty-a-row" contenteditable='true'>2</div><br> <div id="price-a-row" contenteditable='true'>1.00</div><br> <div id="sub-total-a-row" contenteditable='true'></div>

制作 div 輸入並使用 value 屬性,修復 jquery 選擇器修復事件綁定語法刪除 if 條件,真的不知道那是什么

<input id="qty-a-row" contenteditable="true" value="2" /><br />
<input id="price-a-row" contenteditable="true" value="1.00" /><br />
<div id="sub-total-a-row" contenteditable="true"></div>

$("#qty-a-row, #price-a-row").on('change', function () {
    var x = parseInt(document.getElementById("qty-a-row").value);
    var y = parseInt(document.getElementById("price-a-row").value);
    document.getElementById("sub-total-a-row").innerText = (x * y);
});

https://jsfiddle.net/6sh587ve/4/

暫無
暫無

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

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