我有一个第三方估算工具,它始终如一地提供比应该高30%的结果,并且让公司更新工具不是一种选择。那么,我该如何使用Javascript/jQuery DOM调整渲染的数字呢?JavaScript减少了一个类别中的百分比
<div class="general-avg"><strong>$276,000</strong></div>
我想捕获$ 276,000作为一个变量,然后减少30%。任何人都可以解释如何做到这一点? TIA
我有一个第三方估算工具,它始终如一地提供比应该高30%的结果,并且让公司更新工具不是一种选择。那么,我该如何使用Javascript/jQuery DOM调整渲染的数字呢?JavaScript减少了一个类别中的百分比
<div class="general-avg"><strong>$276,000</strong></div>
我想捕获$ 276,000作为一个变量,然后减少30%。任何人都可以解释如何做到这一点? TIA
一般SO社区期望您至少可以尝试自己解决问题的一些代码。这很可能是所有倒票的原因。
但我会认为JS不是你的主要工作,你甚至不知道从哪里开始,所以我会帮助你。
此解决方案不需要任何库,它的工作原理没有jQuery。
// first lets get the divs by class name
var values = document.getElementsByClassName('general-avg');
// then lets go through each of the divs and select strong element inside
[].forEach.call(values, function (item) {
// assumption is that your 3rd party gives you always just one strong tag inside
var strong = item.getElementsByTagName('strong')[0];
// once we have that element selected, take the number from inside, strip $ and remove commas, parse it to float
var newValue = parseFloat(strong.innerText.replace('$','').replace(',',''));
// once we have that, multiply by 0.7 (I sure hope that is how you deduct 30%, otherwise this is emberassing)
newValue = newValue * 0.7;
// once we have that value we just need to format it a bit, this is shameless copy paste from
// http://stackoverflow.com/a/10899795/3963682
var formatNewValue = newValue.toString().split(".");
newValue = formatNewValue[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (formatNewValue[1] ? "." + formatNewValue[1] : "");
// at the end, put the number back in, and add $ sign in front
strong.innerText = '$' + newValue;
});
附在下面是一些JavaScript,将页面加载运行,并会减少30%的任何标签与类名general-avg
var Numbers = document.getElementsByClassName("general-avg");
for (var i = 0; i < Numbers.length; i++) {
Numbers[i].innerText = "$" + Math.round(Number(Numbers[i].innerText.replace(/\D/g, '')) * 0.7).toString().replace(/(...)(.)/g, "$1,$2")
}
代码的演示,可以发现:HERE
断裂完全在其上是不产生圆结果号码:https://jsfiddle.net/ btvLnqyt/4/ –
Miroslav我已经修复它,使它围绕整个n umber:jsfiddle.net/btvLnqyt/5 –
OP没有具体说明在这种情况下发生了什么,你不能只是收集财务数字 –
$('.general-avg strong').each(function() {
var $avgPrice = $(this)
var number = Number($avgPrice[0].innerHTML.replace(/[^0-9\.]+/g,""));
// the 1000s avoid rounding issues
number = number - (number * 0.3 * 1000/1000)
$avgPrice[0].innerHTML = `$${numberWithCommas(number)}`
})
//put the commas back in
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="general-avg"><strong>$100,000</strong></div>
<div class="general-avg"><strong>$276,000</strong></div>
numberWithCommas
功能came from here.
谢谢。我非常感谢。你是对的,JS不是我的主要工作......主要是设计和一些UI的东西。再一次,谢谢......这很有帮助。 –
Miroslav,我将如何四舍五入到最接近的整数?我试过strong.innerText ='$'+ Math.round(Number(newValue));在最后一行,但这不适合我。 –
没关系,我明白了! :) 增加了“newValue = Math.round(newValue);”紧随“newValue = newValue * 0.7;”之后 –