簡體   English   中英

獲取具有相同class的多個項目的值

[英]Get the value of multiple items with the same class

我想獲得具有相同 Class 但內容(數字)不同的多個段落的值。

詳細地說,這些段落包含我想要構建的數字,並將 output 它放入另一個段落。 段落的值由 CMS (Webflow) 傳遞。 我無法在腳本中使用本機 var。

所以我想我必須建立一個數組並得到總數。 + 用.innerHTML輸出。

我是 JavaScript 的新手。

<p class="mwst-price" id="mwst-price"></p>

<script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
    var tax = {totalPrice}+sums*0.19;
    document.getElementById("mwst-price").innerHTML = tax;
</script>
let totalPrice = 0;
document.querySelectorAll('p.myClass').forEach((paragraph) => {
  totalPrice += parseInt(paragraph.innerText);
});

const tax = totalPrice+sums*0.19;
document.querySelector('#mwst-price').innerHTML = tax;

可能您需要這樣的東西,其中“原點”是您要總結的元素的 class。

  function getNumberFromInnerHTML(el) {
    let value = el.innerHTML;
    // convert to number
    value = Number(value.replace(/[^0-9.-]+/g,""));
    return value;
  }
  
  let totalPrice = 0;
  document.getElementsbyClassName('origin').forEach(el => {
    totalPrice += getNumberFromInnerHTML(el);
  }

請參閱此答案以將貨幣字符串轉換為數字。

暫無
暫無

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

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