gpt4 book ai didi

javascript - 获取元素内容并将值的百分比输出到兄弟元素中

转载 作者:行者123 更新时间:2023-12-02 17:11:42 25 4
gpt4 key购买 nike

我有一个页面,其中包含一系列带有价格的产品。在同级元素中的这些价格旁边,我需要输出原始价格的百分比值以及一些解释性报价文本。

这些元素没有 ID,只是为了增加复杂性。

我的代码示例如下...

<div class="info">
<div class="figure">£<span>300.00</span></div>
<div class="offer"><!--percentage goes here--></div>
</div>

<div class="info">
<div class="figure">£<span>450.00</span></div>
<div class="offer"><!--percentage goes here--></div>
</div>

到目前为止我的 jquery 看起来像这样......

var str = $( ".figure span" ).text();
$(".offer").html( str/100*5 ).prepend ("£").append( " spread over xx months" );

这会在“优惠”div 中正确返回 xx 个月内的 22.5 英镑差价。

如果我只在页面上使用它一次,这很棒,但它会在页面上重复使用不同的数字,并且当我这样做时,百分比将不会输出。所以我的问题是如何让它适用于重复元素。

我还需要将结果数字保留到小数点后两位。我知道我应该使用 .toFixed(2) 但我不太确定应该如何在这里应用它。

最佳答案

这是一个演示 http://jsfiddle.net/4wXN7/2/

对于每个信息图,获取其值并将其应用于下一个同级,即offer

$('.info .figure').each(function(){
var str = $(this).text().replace('£','');
$(this).next().html( (str/100*5).toFixed(2) ).prepend ("£").append( " spread over xx months" );
});

关于javascript - 获取元素内容并将值的百分比输出到兄弟元素中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24770401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com