使用jQuery,四舍五入和提交匹配元素的最佳方式

With jQuery, best way to round off and commify matched elements?

本文关键字:元素 最佳 方式 提交 jQuery 四舍五入 使用      更新时间:2023-09-26

在给定的页面上有多个(通常是4个)元素,它们以数字字符串的形式显示原始数据。我想四舍五入并提交每一个,这样它就会显示332,974而不是332974.0。我有正确的commit函数,但我不能让它匹配并正确修改每个匹配的元素。我有:

function formatScore(x) {
    return x.toString().replace(/'B(?=('d{3})+(?!'d))/g, ",");
}
$('.scoreboard .score p').text(formatScore($(this).text()));

<div class="scoreboard">...
   <div class="score"><p>342352343</p></div>...
   <div class="score"><p>243523432.0</p></div>...
   <div class="score"><p>30980943.3</p></div>...
   <div class="score"><p>78908794.0</p></div>...
</div>

让我们来分析一下你的代码:

var text = $(this).text();
var formatted = formatScore(text);
$(".scoreboard .score p").text(formatted);

希望这表明你做错了什么-如果没有别的,你设置所有的元素具有相同的值!

相反,尝试:

$(".scoreboard .score p").text(function(_,score) {return formatScore(score);});

另见文档

试试accounting.js。它对我的项目很有用。

http://josscrowcroft.github.io/accounting.js/