我被分配了一个任务,我已经超越了我对 Javascript 的新手理解。我想知道是否有人可以提供更好的答案。 任务是附加跨度以包括 10% 的折扣并显示新价格。
这是简单的 HTML:
<div>
<p>
<span class="price">$26.99</span>
</p>
</div>
我的(有点混乱)javascript:
// GRAB THE TEXT IN THE PRICE SPAN AND MODIFY IT TO A NUMBER
var price = document.getElementsByClassName("price")[0].lastChild.data.replace('$', '');
console.log(price);
// CREATE DISCOUNT PRICE
const discount = price * 10/100;
console.log(discount.toFixed(2));
// CREATE NEW PRICE
const total = price - discount.toFixed(2);
console.log(total);
`your text`document.write(`$${price} (10% discount) = $${total} `);
不幸的是,我无法正确附加跨度。不确定这是最好的编码方式。
可以设置
textContent
元素的<span>
const priceEl = document.querySelector('span.price');
const discount = 0.1;
const discountedPrice = (priceEl.textContent.slice(1) * (1 - discount)).toFixed(2);
priceEl.textContent = `${priceEl.textContent} (10% discount) = $${discountedPrice}`;
<div>
<p>
<span class="price">$26.99</span>
</p>
</div>
// GRAB THE TEXT IN THE PRICE SPAN AND MODIFY IT TO A NUMBER
var price = parseFloat(document.getElementsByClassName("price")
[0].innerText.replace('$', ''));
// CREATE DISCOUNT PRICE
const discount = price * 0.1;
// CREATE NEW PRICE
const total = price - discount;
// APPEND NEW SPAN WITH DISCOUNTED PRICE
var newSpan = document.createElement("span");
newSpan.className = "discounted-price";
newSpan.innerHTML = `$${total.toFixed(2)}`;
document.getElementsByClassName("price")[0].appendChild(newSpan);
// APPEND TEXT TO SHOW DISCOUNT
var discountText = document.createTextNode(` (10% discount) =
$${price.toFixed(2)}`);
document.getElementsByClassName("price")[0].appendChild(discountText);