首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >循环遍历无序列表并对每个节点Javascript执行操作

循环遍历无序列表并对每个节点Javascript执行操作
EN

Stack Overflow用户
提问于 2015-11-30 22:21:07
回答 3查看 124关注 0票数 0

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

我可以对此进行DOM操作,但我不知道如何循环这些产品。下面的代码仅将第一个产品的销售价格附加到列表中的所有产品。

工频:https://jsfiddle.net/m5fxnLqp/1/

示例HTML:

代码语言:javascript
运行
复制
<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操作:

代码语言:javascript
运行
复制
//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 );
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-11-30 22:25:56

您需要使用.each()循环通过".ProductPrice"

代码语言:javascript
运行
复制
//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 );

    });

Working Demo Here

注意:此代码将通过以下方式追加折扣后的新价格

代码语言:javascript
运行
复制
var priceDiscount = priceNum - priceNum * .30;

如果你只需要一个折扣,就把它还给你的代码。

代码语言:javascript
运行
复制
var priceDiscount = priceNum * .30;

我觉得你需要用

代码语言:javascript
运行
复制
$(this).closest('product').append( formattedPrice );

而不是

代码语言:javascript
运行
复制
$(this).append( formattedPrice );

$(this).append( formattedPrice );$(this).closest('product').append( formattedPrice );的区别

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

代码语言:javascript
运行
复制
<div class="ProductPrice">
     $9.99
     <div style="color:red;"> $6.99</div>
</div>

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

代码语言:javascript
运行
复制
<li class="product">
    <div class="ProductPrice">$9.99</div>
    <div style="color:red;"> $6.99</div>
</li>
票数 2
EN

Stack Overflow用户

发布于 2015-11-30 22:26:38

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

票数 0
EN

Stack Overflow用户

发布于 2015-11-30 22:32:52

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

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

现在起作用了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34009101

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档