You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将修改后的价格数组渲染到现有HTML的li和span元素中?

问题:将计算后的价格渲染回对应HTML元素

现有HTML代码

<ul class="prices-tier items">
   <li class="item">
      <span class="price-container price-tier_price tax weee">
      <span data-price-amount="207.53" data-price-type="" class="price-wrapper "><span class="price">207,53&nbsp;€</span></span>
      </span>
      </span> <strong class="benefit"><span class="percent tier-0">&nbsp;10</span>%</strong>                            
   </li>
   <li class="item">
      <span class="price-container price-tier_price tax weee">
      <span id="1" data-price-amount="196" data-price-type="" class="price-wrapper "><span class="price">196,00&nbsp;€</span></span>
      </span>
      <span id="TaxInfo">
      </span>  <strong class="benefit">risparmia<span class="percent tier-1">&nbsp;15</span>%</strong>                            
   </li>
</ul>

已编写的JS代码

var tierArray = jQuery('.items  li').find('span.price-tier_price > span[data-price-type=""]').map(function() {return jQuery(this).attr('data-price-amount');}).get();
var final = function(x) {
return x * 1.10;
}
var tierformatedPrice = [];
tierArray.forEach(function(item) {
item = final(item);
tieritem = priceUtils.formatPrice(parseInt(item));
tierformatedPrice.push(tieritem);
});

解决方案

方式一:优化流程(推荐)

直接遍历目标元素,同时完成计算与更新,省去单独存储数组的步骤,代码更简洁高效:

jQuery('.items li').find('span.price-tier_price > span[data-price-type=""]').each(function() {
    // 获取原始价格并转为浮点数
    var originalPrice = parseFloat(jQuery(this).attr('data-price-amount'));
    // 计算税后价格
    var calculatedPrice = originalPrice * 1.10;
    // 格式化价格
    var formattedPrice = priceUtils.formatPrice(calculatedPrice);
    // 更新页面显示的价格
    jQuery(this).find('.price').text(formattedPrice);
    // 可选:同步更新data-price-amount属性,保持数据一致性
    jQuery(this).attr('data-price-amount', calculatedPrice.toFixed(2));
});

方式二:基于现有代码修改

如果要保留你已有的tierformatedPrice数组,可添加以下代码完成渲染:

// 获取所有需要更新的.price元素
var priceElements = jQuery('.items li').find('span.price-tier_price > span[data-price-type=""] .price');
// 遍历数组,将格式化后的价格逐个写入对应元素
tierformatedPrice.forEach(function(formattedPrice, index) {
    if (priceElements[index]) {
        jQuery(priceElements[index]).text(formattedPrice);
        // 可选:同步更新data-price-amount属性
        var updatedAmount = (parseFloat(tierArray[index]) * 1.10).toFixed(2);
        jQuery(priceElements[index]).closest('[data-price-amount]').attr('data-price-amount', updatedAmount);
    }
});

注意事项

  • 确认priceUtils.formatPrice返回的结果包含货币符号(如€),若未包含,需自行拼接,例如:formattedPrice + ' €'
  • 原HTML存在标签闭合错误(如<strong class="benefit"未闭合),建议先修复,避免DOM操作异常
  • 若需要保留非断空格&nbsp;,可改用html()方法替代text(),但需注意防范XSS风险

内容的提问来源于stack exchange,提问作者Petacchi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 14:07:53