搜索

首页  >  问答  >  正文

对多个元素进行循环遍历并计算每个元素的价格折扣

<p>我正在尝试找到每个个体<code><div></code>的旧价格和新价格之间的百分比差异。目前,我的代码只能获取第一个<code><div></code>的百分比差异,并将相同的百分比差异循环到其余的<code><div></code>中。有人知道如何更新此代码以针对每个个体<code><div></code>而不仅仅是循环第一个吗?我想使用纯JavaScript实现这个功能,不需要jQuery。</p> <p> <pre class="brush:js;toolbar:false;">const priceDifference = () => { const regPrice = document.querySelector('.old').innerText; const salePrice = document.querySelector('.new').innerText; const priceNumReg = parseFloat(regPrice.substring(1)); const priceNumSale = parseFloat(salePrice.substring(1)); const finalPrice = priceNumReg - priceNumSale; const percentage = document.querySelectorAll('.percentage'); const percent = (finalPrice / priceNumReg) * 100; for (i = 0; i < percentage.length; i++) { if (percentage[i].textContent.trim() === '') { percentage[i].textContent += ' (' + percent.toFixed(0) + '% OFF)'; } } }; priceDifference();</pre> <pre class="brush:html;toolbar:false;"><div class="price"> <div class="old">$14.00</div> <div class="new">$6.00</div> <div class="percentage"></div> </div> <div class="price"> <div class="old">$12.00</div> <div class="new">$5.00</div> <div class="percentage"></div> </div> <div class="price"> <div class="old">$18.00</div> <div class="new">$3.00</div> <div class="percentage"></div> </div></pre> </p>
P粉506963842P粉506963842477 天前528

全部回复(1)我来回复

  • P粉616383625

    P粉6163836252023-09-03 10:41:22

    你必须循环遍历每个.price元素,而不是每个.percentage,因为你试图执行的每个单独的计算都是基于一个单独的<div class="price">的范围。

    在循环内部进行所有的计算,比如当前的priceElement(它是你的<div class="price">元素之一)。

    现在你可以使用priceElement.querySelector,而不是document.querySelector

    document.querySelector在整个文档中找到第一个匹配的元素,而priceElement.querySelector将在该范围内找到第一个匹配的元素:priceElement

    所以函数看起来更像这样:

    const priceDifference = () => {
      const price = document.querySelectorAll(".price");
    
      for (i = 0; i < price.length; i++) {
        const priceElement = price[i];
    
        const regPrice = priceElement.querySelector(".old").innerText;
        const salePrice = priceElement.querySelector(".new").innerText;
        const percentage = priceElement.querySelector(".percentage");
    
        const priceNumReg = parseFloat(regPrice.substring(1));
        const priceNumSale = parseFloat(salePrice.substring(1));
    
        const finalPrice = priceNumReg - priceNumSale;
        const percent = (finalPrice / priceNumReg) * 100;
        
        if (percentage.textContent.trim() === '') {
          percentage.textContent += ' (' + percent.toFixed(0) + '% OFF)';
        }
      }
    };
    

    这段代码是有效的,但仍然有一些工作需要完成,比如缺少i的声明和innerText vs. textContent,但这段代码也可以像这样缩短:

    const parseCurrencyValue = ({ textContent }) => Number.parseFloat(textContent.replace(/^[^-+0-9.]*/u, "")),
      priceDifference = () => Array.from(document.querySelectorAll(".price"))
      .forEach((priceElement) => {
        const [
            regularPrice,
            salePrice
          ] = [ ".old", ".new" ]
            .map((selector) => parseCurrencyValue(priceElement.querySelector(selector))),
          discount = 1 - (salePrice / regularPrice),
          percentageElement = priceElement.querySelector(".percentage");
    
        if (percentageElement.textContent.trim() === "") {
          percentageElement.insertAdjacentText("beforeend", ` (${Math.round(discount * 100)} % off)`);
        }
      });
    
    priceDifference();
    .percentage {
      text-transform: uppercase;
    }
    <div class="price">
      <div class="old">.00</div>
      <div class="new">.00</div>
      <div class="percentage"></div>
    </div>
    
    <div class="price">
      <div class="old">.00</div>
      <div class="new">.00</div>
      <div class="percentage"></div>
    </div>
    
    <div class="price">
      <div class="old">.00</div>
      <div class="new">.00</div>
      <div class="percentage"></div>
    </div>

    回复
    0
  • 取消回复