简体   繁体   中英

Using template literals in Javascript

So I'm making a shopping cart and I'm adding products dynamically, and each product have multiple elements of course but my problem is in the remove button and in the add amount, remove amount and the item quantity. Each of those has a class but I can't choose those elements because I'm commenting them out or removing them from the HTML. So is there a way to grab those elements by adding classes to them using template literals?

Here's my single product HTML:

<div class="cart-content">
  <!-- cart item -->
  <!-- <div class="cart-item">
    <img src="/img/higher-clouds.jpg" alt="product" srcset="" />
    <div>
      <h4>queen bed</h4>
      <h5>$9</h5>
      <span class="remove-item">Remove</span>
    </div>
    <div>
      <i class="fas fa-chevron-up"></i>
      <p class="item-amount">1</p>
      <i class="fas fa-chevron-down"></i>
    </div>
  </div> -->
  <!-- end of cart item -->
</div>

And this is the javascript:

// add products to cart

const addBtns = document.getElementsByClassName("bag-btn");
for (let i = 0; i < addBtns.length; i++) {
  const btn = addBtns[i];
  btn.addEventListener("click", addToCart);
}

function addToCart(e) {
  const button = e.target;
  button.innerText = "In Cart";
  button.disabled = true;
  const title = button.parentElement.nextElementSibling.textContent;
  const price =
  button.parentElement.nextElementSibling.nextElementSibling.children[0].textContent;
  const img = button.parentElement.children[0].src;
  addItemToCart(title, price, img);
}

function addItemToCart(title, price, img) {
  const newRow = document.createElement("div");
  newRow.classList.add("cart-item");
  newRow.innerHTML = `
 <img src="${img}" alt="product" srcset="" />
  <div>
    <h4>${title}</h4>
    <h5>${price}</h5>
    <span class="remove-item">Remove</span>
  </div>
  <div>
    <i class="fas fa-chevron-up"></i>
    <p class="item-amount">1</p>
    <i class="fas fa-chevron-down"></i>
  </div>`;
  cartContent.append(newRow);
}

How to add the classes (remove-item, fa-chevron-up, fa-chevron-down, item-amount) to their elements using template literals or any other way? Any help would be appreciated.

use this pattern, attribute="${dynamicValue}" notice the quotes(" ") around the template expression.

  `<div>
    <i class="${dynamicString} ${dynamicString}"></i>
    <p class="${dynamicString}">1</p>
    <i class="${dynamicString}"></i>
  </div>`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM