我的代码中有一些数字,我想总结。
<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
中答案 0 :(得分:4)
您可以使用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>
答案 1 :(得分:1)
如果您使用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
查找总和并存储在变量中,使用该变量进行显示。
答案 2 :(得分:0)
检查此fiddle
var total = 0;
$( ".product__description__property" ).each( function() {
var valueArr = $.trim( $( this ).html() ).split( " " ) ;
console.log( valueArr );
total += parseFloat( valueArr[ 1 ]);
} );
console.log( total );