简体   繁体   English

在 Javascript 中使用模板文字

[英]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.其中每一个都有一个 class 但我无法选择这些元素,因为我将它们注释掉或从 HTML 中删除它们。 So is there a way to grab those elements by adding classes to them using template literals?那么有没有办法通过使用模板文字向它们添加类来获取这些元素?

Here's my single product HTML:这是我的单品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:这是 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?如何使用模板文字或任何其他方式将类(remove-item、fa-chevron-up、fa-chevron-down、item-amount)添加到它们的元素中? Any help would be appreciated.任何帮助,将不胜感激。

use this pattern, attribute="${dynamicValue}" notice the quotes(" ") around the template expression.使用这种模式, attribute="${dynamicValue}"注意模板表达式周围的引号(" ")。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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