添加购物车在ES6中不起作用(java脚本) [英] Add cart not working in ES6 (java script)

查看:119
本文介绍了添加购物车在ES6中不起作用(java脚本)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我有问题。添加到购物车功能无法正常工作。单击添加到购物车按钮后,如果它是相同的产品ID,则会在另一行上输出新产品。另一个问题是购物车中的总金额。



我尝试了什么:



我尝试使用find函数但它仍然不起作用。它仍然在另一行输出新产品。请帮我解决这个问题。谢谢。顺便说一句,这是我下面的代码。



<!DOCTYPE html> 
< html>
< head>
< title>购物车ES6 < / title >
< / head >
< body>
< form name = order id = order>
< table>
< tr>
< td>
< label = productID >产品ID:< / label >
< / td >
< td>
< input id = productID name = product type = text size = 28 required />
< / td >
< / tr >
< tr>
< td>
< label for = product >产品说明:< / label >
< / td >
< td>
< input id = product_desc name = product type = text size = 28 required />
< / td >
< / tr >
< tr>
< td>
< label for = quantity >数量:< / 标签 >
< / td >
< td>
< input id = quantity name = 数量 width = 196px需要/>
< / td >
< / tr >
< tr>
< td>
< label = price >价格:< / 标签 >
< / td >
< td>
< input id = price name = price size = 需要28 />
< / td >
< / tr >
< / table >
< input type = reset class = resetbtn value = 重置 />
< input type = button id = btnAddProduct onclick = addProduct(); value = 添加新产品>
< / 表格 >
< table border = 1 | 1 id = products-table>
< tr>
< th>产品ID < / th >
< th>产品说明< / th >
< th>数量< / >
< th>价格< / < span class =code-leadattribute> th >
< th>操作< ; / th >
< / tr >
< / 表格 >
< br />
< h2>购物车< / h2 >
< table border = 1 | 1 id = carts-table>
< tr>
< th>产品ID < / th >
< th>产品说明< / th >
< th>数量< / >
< th>价格< / < span class =code-leadattribute> th
>
< th>总金额 < / th >
< th>行动< / th >
< span class =code-keyword>< /
tr >
< / table >
< / body >
< script src = script.js >
< / script>
< / html >

< script>
// JS文件

const products = [];
const carts = [];
const inputs = {
id: document .getElementById( productID),
desc: document .getElementById( product_desc),
数量: document .getElementById( quantity),
price:< span class =code-sdkkeyword> document
.getElementById( price
};
const productsTable = document .getElementById( products-table);
const cartsTable = document .getElementById( carts-table);

function renderProductsTable(){
// 删除所有条目
数组 .from(productsTable.children).slice( 1 )。forEach(entry =& gt; productsTable.removeChild(entry));

for (产品的产品){
const tr = document .createElement(' tr') ;
const id = document .createElement(' td');
id.textContent = product.id;
const desc = document .createElement(' td');
desc.textContent = product.desc;
const qty = document .createElement(' td');
qty.textContent = product.qty;
const price = document .createElement(' td');
price.textContent = product.price;
const action = document .createElement(' td');
const deleteButton = document .createElement(' button');
deleteButton.textContent = ' 删除';
deleteButton.addEventListener(' click',()=& gt; removeProduct(product .id))
const addToCartButton = document .createElement(' button');
addToCartButton.textContent = ' 添加到购物车';
addToCartButton.addEventListener(' click',()=& gt; addCart(product 。ID));
action.appendChild(deleteButton);
action.appendChild(addToCartButton);
tr.appendChild(id);
tr.appendChild(desc);
tr.appendChild(qty);
tr.appendChild(price);
tr.appendChild(action);
productsTable.appendChild(tr);
console .log(产品);
}

}

function addProduct(){

< span class =code-keyword> const
product = {
id:inputs.id.value,
desc:inputs.desc.value,
qty: Number (inputs.qty.value),
price: Number (inputs.price.value)
};

existing = products.find(item =& gt; item.id === product.id);

if (现有){
existing.qty + = product.qty;
}
else {
products.push(product);
}
renderProductsTable();
document .getElementById(' order'< /跨度>)复位();
}



function removeProduct(product_id){
const index = products.findIndex(p =& gt; p.id === product_id);
products.splice(index, 1 );
renderProductsTable();
}

function addCart(product_id){
const product = products.find(p =& gt; p.id === product_id);
const cartItem = carts.find(c =& gt; c.product === product);
if (cartItem){
cartItem.qty + = 1 ;
}
else {
carts.push(product);
}
renderCartTable();
console .log(cartItem);
}

function renderCartTable(){
for (推车购物车){
const tr = document .createElement(' tr');
const id = document .createElement(' td');
id.textContent = cart.id;
const desc = document .createElement(' td');
desc.textContent = cart.desc;
const qty = document .createElement(' td');
qty.textContent = cart.qty;
const price = document .createElement(' td');
price.textContent = cart.price;
const total = document .createElement(' td');
total.textContent = 总金额应自动计算在这里
const action = document .createElement(' TD');
const subtractButton = document .createElement(' button');
subtractButton.textContent = ' 减去数量';
const addButton = document .createElement(' button');
addButton.textContent = ' 添加数量';
const removeButton = document .createElement(' button');
removeButton.textContent = ' 删除项目';
tr.appendChild(id);
tr.appendChild(desc);
tr.appendChild(qty);
tr.appendChild(price);
tr.appendChild(总计);
tr.appendChild(action);
cartsTable.appendChild(tr);
console .log(carts);
}
}
< / script>

解决方案

这里是jsfiddle:

添加购物车无法正常工作 - JSFiddle [ ^ ]



但它按预期工作。



我做了一些改动只是为了让它运行,比如填充doc.ready上的元素,只是为了让它适合jsfiddle。



我还使功能箭头功能。



我想我加载脚本时没有得到?也许到运行时文档还没有完成加载所有元素?



尝试查看jQuery。它适用于ES6。您可以设置选择器,而不是查找元素,选择器用作指向匹配元素的指针。这是一种更加一致的方式来掌握你的元素。在这里,看看:



  id =  document  .getElementById(  productID
< span class =code-comment> // 如果元素尚未加载,则id将为null
id =

productID
// 这将在调用时进行评估。它将返回一个数组btw


Hi Guys, I have a problem. The add to cart function doesn't work correctly. After i clicked the add to cart button, if it is the same Product ID, it does output a new product on another row. Another problem, is the total amount in the cart table.

What I have tried:

I tried using the find function but it still doesn't work. It still output a new product on another row. Please help me fix this. Thank you. BTW, here's my code below.

<!DOCTYPE html>
<html>
<head>
  <title>Shopping Cart ES6</title>
</head>
<body>
  <form name="order" id="order">
    <table>
      <tr>
        <td>
          <label for="productID">Product ID:</label>
        </td>
        <td>
          <input id="productID" name="product" type="text" size="28" required/>
        </td>
      </tr>
      <tr>
          <td>
              <label for="product">Product Desc:</label>
          </td>
          <td>
              <input id="product_desc" name="product" type="text" size="28" required/>
          </td>
      </tr>
      <tr>
          <td>
              <label for="quantity">Quantity:</label>
          </td>
          <td>
              <input id="quantity" name="quantity" width="196px" required/>
          </td>
      </tr>
      <tr>
          <td>
              <label for="price">Price:</label>
          </td>
          <td>
              <input id="price" name="price" size="28" required/>
          </td>
      </tr>
  </table>
  <input type="reset" class="resetbtn" value="Reset" />
  <input type="button" id="btnAddProduct" onclick="addProduct();" value="Add New Product" >
</form>
<table border="1|1" id="products-table">
  <tr>
    <th>Product ID</th>
    <th>Product Description</th>
    <th>Quantity</th>
    <th>Price</th>
    <th>Action</th>
  </tr>
</table>
<br />
<h2>Shopping Cart</h2>
<table border="1|1" id="carts-table">
  <tr>
    <th>Product ID</th>
    <th>Product Description</th>
    <th>Quantity</th>
    <th>Price</th>
    <th>Total Amount</th>
    <th>Action</th>
  </tr>
</table>
</body>
<script src="script.js">
</script>
</html>
 
<script>
//JS File

const products = [];
const carts = [];
const inputs = {
  id: document.getElementById("productID"),
  desc: document.getElementById("product_desc"),
  qty: document.getElementById("quantity"),
  price: document.getElementById("price")
};
const productsTable = document.getElementById("products-table");
const cartsTable = document.getElementById("carts-table");

function renderProductsTable() {
  // delete all entries
  Array.from(productsTable.children).slice(1).forEach(entry =&gt; productsTable.removeChild(entry));
    
    for (product of products) {
      const tr = document.createElement('tr');
      const id = document.createElement('td');
      id.textContent = product.id;
      const desc = document.createElement('td');
      desc.textContent = product.desc;
      const qty = document.createElement('td');
      qty.textContent = product.qty;
      const price = document.createElement('td');
      price.textContent = product.price;
      const action = document.createElement('td');
      const deleteButton = document.createElement('button');
      deleteButton.textContent = 'Delete';
      deleteButton.addEventListener('click', () =&gt; removeProduct(product.id))
      const addToCartButton = document.createElement('button');
      addToCartButton.textContent = 'Add to cart';
      addToCartButton.addEventListener('click', () =&gt; addCart(product.id));
      action.appendChild(deleteButton);
      action.appendChild(addToCartButton);
      tr.appendChild(id);
      tr.appendChild(desc);
      tr.appendChild(qty);
      tr.appendChild(price);
      tr.appendChild(action);
      productsTable.appendChild(tr);
      console.log(products); 
    }

}

function addProduct() {
  
  const product = {
  id: inputs.id.value,
  desc: inputs.desc.value, 
  qty: Number(inputs.qty.value),
  price: Number(inputs.price.value)
  };

  let existing = products.find(item =&gt; item.id === product.id);

  if (existing) {
  existing.qty += product.qty;
  } 
  else {
   products.push(product);
  }
  renderProductsTable();
  document.getElementById('order').reset();
  }



function removeProduct(product_id) {
  const index = products.findIndex(p =&gt; p.id === product_id);
  products.splice(index, 1);
  renderProductsTable();
}

function addCart(product_id) {
      const product = products.find(p =&gt; p.id === product_id);
      const cartItem = carts.find(c =&gt; c.product === product);
      if(cartItem) {
        cartItem.qty += 1;
      }
      else {
        carts.push(product);
      }
      renderCartTable();
            console.log(cartItem);
}

function renderCartTable() {
  for (cart of carts){
    const tr = document.createElement('tr');
    const id = document.createElement('td');
    id.textContent = cart.id;
    const desc = document.createElement('td');
    desc.textContent = cart.desc;
    const qty = document.createElement('td');
    qty.textContent = cart.qty;
    const price = document.createElement('td');
    price.textContent = cart.price;
    const total = document.createElement('td');
    total.textContent = "Total Amount Should Calculate Here Automatically"
    const action = document.createElement('td');
    const subtractButton = document.createElement('button');
    subtractButton.textContent = 'Subtract Quantity';
    const addButton = document.createElement('button');
    addButton.textContent = 'Add Quantity';
    const removeButton = document.createElement('button');
    removeButton.textContent = 'Remove Item';
    tr.appendChild(id);
    tr.appendChild(desc);
    tr.appendChild(qty);
    tr.appendChild(price);
    tr.appendChild(total);
    tr.appendChild(action);
    cartsTable.appendChild(tr);
    console.log(carts);
  }
}
</script>

解决方案

Here it is in jsfiddle:
Add cart not working - JSFiddle[^]

But it works as expected.

I made a couple of changes just to get it to run, such as populating the elements on doc.ready, just to get it to fit with jsfiddle.

I also made the functions arrow functions.

I guess I don't get when you load the script? Maybe by the time it runs the document hasn't finished loading all the elements?

Try looking at jQuery. It works great with ES6. Instead of looking for the element you can set selectors, which act as pointers to elements that match. It's a much more consistent way of getting hold of your elements. Here, look:

let id = document.getElementById("productID")
//id will be null if the element hasn't loaded yet
id =


("productID") //this will be evaluated when it's called. It will return an array btw


这篇关于添加购物车在ES6中不起作用(java脚本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆