求和字符串在<span></span>使用javascript

Sum string inside <span> </span> with javascript

本文关键字:span gt lt 使用 javascript 字符串 求和      更新时间:2023-09-26

我的代码中span内有一些数字要求和。

<span class="product__description__property order-summary__small-text">
            weight: 0.1 lb
          </span>
<span class="product__description__property order-summary__small-text">
            weight: 0.5 lb
          </span>
<span class="product__description__property order-summary__small-text">
            weight: 0.2 lb
          </span>
           .
           .
           .

我想求和0.1+0.5+…+n=总数,并将总数存储在变量X 中

您可以使用getElementsByClassName()product__description__property类的所有跨度为目标,使用regex从字符串中提取数字,查看下面的示例。

希望这能有所帮助。


var spans = document.getElementsByClassName('product__description__property');
var total = 0;
for ( var i=0 ; i<spans.length; i++){
  var span_text = spans[i].textContent;
  var span_number =  parseFloat ( span_text.match(new RegExp("weight: (.*) lb"))[1] );
  total += span_number;
}
document.getElementById('total').textContent = total;
<span class="product__description__property order-summary__small-text">
  weight: 0.1 lb
</span>
<span class="product__description__property order-summary__small-text">
  weight: 0.5 lb
</span>
<span class="product__description__property order-summary__small-text">
  weight: 0.2 lb
</span>
<br>
<br>
Total : <span id='total'></span>

如果您使用jquery

var total = 0;
$(".product__description__property").each(function(d) {
  var value = $(this).text().replace("weight: ", "").replace(" lb", "");
  total += +value;
});
document.write("<br/>Total:"+total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="product__description__property order-summary__small-text">
            weight: 0.1 lb
          </span>
<span class="product__description__property order-summary__small-text">
            weight: 0.5 lb
          </span>
<span class="product__description__property order-summary__small-text">
            weight: 0.2 lb
          </span>

您需要使用.each来找到您的和并存储在一个变量中,使用该变量来显示。

检查这个小提琴

var total = 0;
$( ".product__description__property" ).each( function() {  
  var valueArr = $.trim( $( this ).html() ).split( " " ) ;
  console.log( valueArr );
  total += parseFloat( valueArr[ 1 ]);
} );
console.log( total );