Rumah > Soal Jawab > teks badan
P粉6163836252023-09-03 10:41:22
Anda perlu mengulangi julat setiap .price
元素,而不是每个.percentage
,因为你试图执行的每个单独的计算都是基于一个单独的<div class="price">
.
Adakah semua pengiraan di dalam gelung, iaitu salah satu daripada priceElement
(它是你的<div class="price">
elemen semasa).
Kini anda boleh menggunakan priceElement.querySelector
,而不是document.querySelector
.
document.querySelector
在整个文档中找到第一个匹配的元素,而priceElement.querySelector
将在该范围内找到第一个匹配的元素:priceElement
.
Jadi fungsinya kelihatan lebih seperti ini:
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)'; } } };
Kod ini sah, tetapi masih ada beberapa kerja yang perlu dilakukan, seperti tiada i
的声明和innerText
vs. textContent
, tetapi kod ini juga boleh dipendekkan seperti ini:
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>