繁体   English   中英

遍历无序列表并在每个节点上执行操作Javascript

[英]Loop through unordered list and perform operation on each node Javascript

我的商店里有产品清单。 每个产品的价格都以div为单位。 我需要找到每种产品的价格,并计算出30%的销售价格,并将其附加到红色的价格中。

我可以为此进行DOM操作,但无法弄清楚如何对产品进行循环。 下面的代码将仅第一个产品的销售价格附加到列表中的所有产品。

工作小提琴: https//jsfiddle.net/m5fxnLqp/1/

HTML示例:

<ul class="ProductList">
  <li class="product">
    <div class="ProductPrice">$9.99</div>
  </li>
  <li class="product">
    <div class="ProductPrice">$10.99</div>
  </li>
</ul>

这是DOM操作:

//find the price and convert to decimal to work with
var price = $(".ProductPrice").text();
var priceFormat = price.replace("$", "");
var priceNum = parseFloat(priceFormat).toFixed(2);

//calculate the price discount 
var priceDiscount = priceNum * .30;
var priceFinal = priceDiscount.toFixed(2);

// Append the formatted price to the div
var formattedPrice = '<div style="color:red;"> $' + priceFinal + '</div>';
$(".ProductPrice").append( formattedPrice );

您需要使用.each()遍历".ProductPrice"

//find the price and convert to decimal to work with
   $(".ProductPrice").each(function(){
        var price = $(this).text();
        var priceFormat = price.replace("$", "");
        var priceNum = parseFloat(priceFormat).toFixed(2);

        //calculate the price discount 
        var priceDiscount = priceNum - priceNum * .30;
        var priceFinal = priceDiscount.toFixed(2);

        // Append the formatted price to the div
        var formattedPrice = '<div style="color:red;"> $' + priceFinal + '</div>';
        $(this).append( formattedPrice );

    });

在这里工作演示

注意:此代码将通过使用折扣后的价格附加新价格

var priceDiscount = priceNum - priceNum * .30;

如果您只需要折扣,请将其返回您的代码

var priceDiscount = priceNum * .30;

我认为你需要使用

$(this).closest('product').append( formattedPrice );

代替

$(this).append( formattedPrice );

$(this).append( formattedPrice );之间的差异$(this).append( formattedPrice ); $(this).closest('product').append( formattedPrice );

$(this).append( formattedPrice ); 追加后的html

<div class="ProductPrice">
     $9.99
     <div style="color:red;"> $6.99</div>
</div>

$(this).closest('product').append( formattedPrice ); 追加后的html

<li class="product">
    <div class="ProductPrice">$9.99</div>
    <div style="color:red;"> $6.99</div>
</li>

我相信您正在寻找.each函数: http ://api.jquery.com/each/

我使用each()函数更新您的代码:

https://jsfiddle.net/m5fxnLqp/4/

现在可以了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM