如何将 JavaScript 整合到 HTML 页面中

How to integrate JavaScript into a HTML page

我正在尝试创建一个 HTML 网站来销售钢笔、铅笔和橡皮。我的问题是将 JavaScript 整合到我的 HTML 页面中。在 JavaScript 关于如何解决此问题的最后几块之前,一切都正常工作。

<!DOCTYPE html>

<html>

<head>

<title>Pens, Pencils and Erasers</title>

<meta name="description" content="This is the description">

<link rel="stylesheet" href="style.css" />

<script src="store.js" async></script>

</head>

<body>

<header class="main-header">

<nav class="main-nav nav">

<ul>

<li><a href="index.html">HOME</a></li>

</ul>

</nav>

<h1 class="store-name store-name-large">Pens, Pencils and Erasers</h1>

</header>

<section class="container content-section">

<div class="shop-items">

<span class="shop-item-title">Pen</span>

<img class="shop-item-image" src="pen.jpg">

<div class="shop-item-details">

<span class="shop-item-price">[=12=].50</span>

<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>

</div>

</div>

<div class="shop-item">

<span class="shop-item-title">Pencil</span>

<img class="shop-item-image" src="pencil.webp">

<div class="shop-item-details">

<span class="shop-item-price">[=12=].30</span>

<button class="btn btn-primary shop-item-button"type="button">ADD TO CART</button>

</div>

</div>

<div class="shop-item">

<span class="shop-item-title">Eraser</span>

<img class="shop-item-image" src="eraser.png">

<div class="shop-item-details">

<span class="shop-item-price">.00</span>

<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>

</div>

</div>

</section>

<section class="container content-section">

<h2 class="section-header">CART</h2>

<select id = "province">

<option value= "saskatchewan" data-shipping-cost= "0" data-tax= "0.05" data-deal-limiter= "30" data-deal-coupon= "5">Saskatchewan</option>

<option value= "alberta" data-shipping-cost= "2" data-tax= "0.05" data-deal-limiter= "0" data-deal-coupon= "0">Alberta</option>

<option value= "manitoba" data-shipping-cost= "2" data-tax= "0.06" data-deal-limiter= "0" data-deal-coupon= "0">Manitoba</option>

</select>

<div class="cart-row">

<span class="cart-item cart-header cart-column">ITEM</span>

<span class="cart-price cart-header cart-column">PRICE</span>

<span class="cart-quantity cart-header cart-column">QUANTITY</span>

</div>

<div class="cart-items">

</div>

<div class="cart-total">

<strong class="cart-total-title">Total</strong>

<span class="cart-total-price">[=12=]</span><br><br>

</div>

<button class="btn btn-primary btn-purchase" type="button">PURCHASE</button>

</section>

<script>

if (document.readyState == 'loading') {

document.addEventListener('DOMContentLoaded', ready)

} else {

ready()

}

function ready() {

var removeCartItemButtons = document.getElementsByClassName('btn-danger')

for (var i = 0; i < removeCartItemButtons.length; i++) {

var button = removeCartItemButtons[i]

button.addEventListener('click', removeCartItem)

}

var quantityInputs = document.getElementsByClassName('cart-quantity-input')

for (var i = 0; i < quantityInputs.length; i++) {

var input = quantityInputs[i]

input.addEventListener('change', quantityChanged)

}

var addToCartButtons = document.getElementsByClassName('shop-item-button')

for (var i = 0; i < addToCartButtons.length; i++) {

var button = addToCartButtons[i]

button.addEventListener('click', addToCartClicked)

}

document.getElementsByClassName('btn-purchase')[0].addEventListener('click', purchaseClicked)

}

function purchaseClicked() {

alert('Thank you for your purchase')

var cartItems = document.getElementsByClassName('cart-items')[0]

while (cartItems.hasChildNodes()) {

cartItems.removeChild(cartItems.firstChild)

}

updateCartTotal()

}

function removeCartItem(event) {

var buttonClicked = event.target

buttonClicked.parentElement.parentElement.remove()

updateCartTotal()

}

function quantityChanged(event) {

var input = event.target

if (isNaN(input.value) || input.value <= 0) {

input.value = 1

}

updateCartTotal()

}

function addToCartClicked(event) {

var button = event.target

var shopItem = button.parentElement.parentElement

var title = shopItem.getElementsByClassName('shop-item-title')[0].innerText

var price = shopItem.getElementsByClassName('shop-item-price')[0].innerText

var imageSrc = shopItem.getElementsByClassName('shop-item-image')[0].src

addItemToCart(title, price, imageSrc)

updateCartTotal()

}

function addItemToCart(title, price, imageSrc) {

var cartRow = document.createElement('div')

cartRow.classList.add('cart-row')

var cartItems = document.getElementsByClassName('cart-items')[0]

var cartItemNames = cartItems.getElementsByClassName('cart-item-title')

for (var i = 0; i < cartItemNames.length; i++) {

if (cartItemNames[i].innerText == title) {

alert('This item is already added to the cart')

return

}

}

var cartRowContents = `

<div class="cart-item cart-column">

<img class="cart-item-image" src="${imageSrc}" width="100" height="100">

<span class="cart-item-title">${title}</span>

</div>

<span class="cart-price cart-column">${price}</span>

<div class="cart-quantity cart-column">

<input class="cart-quantity-input" type="number" value="1">

<button class="btn btn-danger" type="button">REMOVE</button>

</div>`

cartRow.innerHTML = cartRowContents

cartItems.append(cartRow)

cartRow.getElementsByClassName('btn-danger')[0].addEventListener('click', removeCartItem)

cartRow.getElementsByClassName('cart-quantity-input')[0].addEventListener('change', quantityChanged)

}

function updateCartTotal() {

var cartItemContainer = document.getElementsByClassName('cart-items')[0]

var cartRows = cartItemContainer.getElementsByClassName('cart-row')

var order_total = 0

for (var i = 0; i < cartRows.length; i++) {

var cartRow = cartRows[i]

var priceElement = cartRow.getElementsByClassName('cart-price')[0]

var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]

var price = parseFloat(priceElement.innerText.replace('$', ''))

var quantity = quantityElement.value

order_total = order_total + (price * quantity)

}

order_total = Math.round(order_total * 100) / 100

document.getElementsByClassName('cart-total-price')[0].innerText = '$' + order_total

}

document.getElementById("province").addEventListener("change", function() {

const select = document.getElementById("province")


selectedProvince = select.options[select.selectedIndex]

shippingCost = selectedProvince.dataset.shippingCost 

tax = selectedProvince.dataset.tax

dealLimiter = selectedProvince.dataset.dealLimiter,

dealCoupon = selectedProvince.dataset.dealCoupon;

});

if (selectedProvince.value === saskatchewan) {

shippingCost = "0"

tax = order_total * 0.05

dealLimiter = "30"

dealCoupon = "5"

document.getElementById("cart-subtotal-price").value = order_total + shippingCost + tax - dealCoupon

}

if (selectedProvince.value === alberta) { 

shippingCost = "2"

tax = order_total * 0.05 

dealLimiter = "0" 

dealCoupon = "0" 

document.getElementById("cart-subtotal-price").value = order_total + shippingCost + tax - dealCoupon 

} if (selectedProvince.value === manitoba) { 

shippingCost = "2" 

tax = order_total * 0.06 

dealLimiter = "0" 

dealCoupon = "0"

document.getElementById("cart-subtotal-price").value = order_total + shippingCost + tax - dealCoupon 

}

</script>

</body>

</html

我希望如果选择萨斯喀彻温省,它应该对销售价格征收 5% 的税,如果他们花费 30 美元,他们将减去 5 美元。如果选择艾伯塔省,他们将获得 2 美元的运费和销售价格上的 5% 税费。如果选择马尼托巴省,他们将获得 2 美元的运费和 6% 的税费。

我已经花时间清理您的代码和其中的错误。请将我下面的代码片段与您的代码进行比较以了解问题所在。

您将能够复制粘贴它来替换旧代码,它会像我处理您最初的代码一样工作。

function updateCartTotal() {
    const cartItemContainer = document.getElementsByClassName('cart-items')[0],
          cartRows = cartItemContainer.getElementsByClassName('cart-row');
    let   sub_total = 0;

    for (let i = 0; i < cartRows.length; i++) {
        const cartRow = cartRows[i],
              priceElement = cartRow.getElementsByClassName('cart-price')[0],
              quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0],
              price = parseFloat(priceElement.innerText.replace('$', '')),
              quantity = quantityElement.value;

        sub_total += (price * quantity); 
    }

    const order_total = Math.round(calculateTotal(sub_total) * 100) / 100;

    document.getElementsByClassName('cart-total-price')[0].innerText = '$' + order_total;
}

function calculateTotal(sub_total){
    const select = document.getElementById("province"),
          selectedProvince = select.options[select.selectedIndex],
          shippingCost = selectedProvince.dataset.shippingCost, 
          tax = selectedProvince.dataset.tax,
          dealLimiter = selectedProvince.dataset.dealLimiter,
          dealCoupon = selectedProvince.dataset.dealCoupon,
          appliedCoupon = parseFloat(sub_total) > parseFloat(dealLimiter) ? parseFloat(dealCoupon) : 0,
          pretotal = ((sub_total + parseFloat(shippingCost) - appliedCoupon)),
          total = pretotal + (pretotal * parseFloat(tax));

    return total;
}

document.getElementById("province").addEventListener("change", calculateTotal());