我有一大块 HTML,它是通过 PHP 生成的,并在一个跨度内生成一个带有两位小数的数字,其类为“amount”:
<span class="amount">200.00</span>
我想要做的是使用客户端方法更改范围内的文本,使其没有小数位(即在本例中为 200),因此我不需要编辑任何原始内容PHP,因为这是通过插件生成的。
欢迎任何想法。
最佳答案
可以使用jQuery的.each
方法循环遍历每个元素,然后使用split方法获取整数部分即可
$(function(){
//Go through each element
$(".amount").each(function(item){
//split the text on the dot, and then take the front piece
$(this).text( $(this).text().split(".")[0] );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="amount">200.00</span><br />
<span class="amount">220.40</span><br />
<span class="amount">5.40</span><br />
<span class="amount">90.95</span><br />
请注意,如果您事先知道这些值将始终具有您可以直接使用的 .00
值
$(this).text( +$(this).text() );
通过强制它是一个数字(通过在前面加上 +)然后变回一个字符串(当它被设置为元素文本时)将导致它丢失小数部分
关于javascript - 删除 DOM 中的小数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26043784/