求和字符串在<span></span>使用javascript
Sum string inside <span> </span> with javascript
我的代码中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 );
相关文章:
- 排序<李><Ul>根据<span>内部<李>
- 如何隐藏空<span>在IE中使用javascript.(注意,在其他浏览器中工作正常)
- 点击功能在<span>
- 如何获得<span>价值
- 将换行符写入<span>元素
- jQuery访问列表视图->ul->李->span->img
- 如何在单击按钮时显示文本(按钮被<span></span>标记包围)
- Kendo UI-将Text()括起来的文本转换为<span>编码HTML
- 充满<span>标签
- 选择2模板<span>文本</span>在选择渲染中
- 如何在<span>在<tr>具有不同行为的标签(onclick)
- 白内障患者可以't点击嵌入式<span>内部<a>要素
- 如何从HTML<输入>元素设置为<span>使用JavaScript.innerHTML
- 用<为纯文本字符串着色;span>元素
- a<span>在DOM中动态附加
- <的缺少单击事件;span>内部<按钮>元素
- 求和字符串在<span></span>使用javascript
- 如何将处理程序附加到<span>
- 如何定位<span>以背景为中心
- 在<span>在<选择>