购物车,单击“添加到购物车”按钮后:价格已添加,但显示为零

时间:2020-09-12 10:53:37

标签: javascript html jquery css

错误:未捕获的类型错误:无法读取未定义(...)的属性“ split”

大家好,我要在购物车模式中添加一些内容,我从 codepen 示例中获得了一些参考,之后我对代码进行了一些更改。后来我运行了,并且出现了上面的错误 我不知道该如何解决,但没有解决.. 当我评论该行时,代码将起作用,但产品成本在购物车中显示为空。只是显示零金额。

js处的错误行:price = parseFloat(x.price.split('₹')[1]);

我的自定义代码笔链接:https://codepen.io/guenon/pen/VwaxXLJ

原始密码笔链接:https://codepen.io/PurpleTigress/pen/eXPxxq

/* get cart total from session on load */
updateCartTotal();

/* button event listeners */
document.getElementById("emptycart").addEventListener("click", emptyCart);
var btns = document.getElementsByClassName('addtocart');
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener('click', function() {
    addToCart(this);
  });
}

/* ADD TO CART functions */

function addToCart(elem) {
  //init
  var sibs = [];
  var getprice;
  var getproductName;
  var cart = [];
  var stringCart;
  //cycles siblings for product info near the add button
  while (elem = elem.previousSibling) {
    if (elem.nodeType === 3) continue; // text node
    if (elem.className == "price") {
      getprice = elem.innerText;
    }
    if (elem.className == "productname") {
      getproductName = elem.innerText;
    }
    sibs.push(elem);
  }
  //create product object
  var product = {
    productname: getproductName,
    price: getprice
  };
  //convert product data to JSON for storage
  var stringProduct = JSON.stringify(product);
  /*send product data to session storage */

  if (!sessionStorage.getItem('cart')) {
    //append product JSON object to cart array
    cart.push(stringProduct);
    //cart to JSON
    stringCart = JSON.stringify(cart);
    //create session storage cart item
    sessionStorage.setItem('cart', stringCart);
    addedToCart(getproductName);
    updateCartTotal();
  } else {
    //get existing cart data from storage and convert back into array
    cart = JSON.parse(sessionStorage.getItem('cart'));
    //append new product JSON object
    cart.push(stringProduct);
    //cart back to JSON
    stringCart = JSON.stringify(cart);
    //overwrite cart data in sessionstorage 
    sessionStorage.setItem('cart', stringCart);
    addedToCart(getproductName);
    updateCartTotal();
  }
}
/* Calculate Cart Total */
function updateCartTotal() {
  //init
  var total = 0;
  var price = 0;
  var items = 0;
  var productname = "";
  var carttable = "";
  if (sessionStorage.getItem('cart')) {
    //get cart data & parse to array
    var cart = JSON.parse(sessionStorage.getItem('cart'));
    //get no of items in cart 
    items = cart.length;
    //loop over cart array
    for (var i = 0; i < items; i++) {
      //convert each JSON product in array back into object
      var x = JSON.parse(cart[i]);
      //get property value of price
      price = parseFloat(x.price.split('₹')[1]);
      productname = x.productname;
      //add price to total
      carttable += "<tr><td>" + productname + "</td><td>₹" + price.toFixed(2) + "</td></tr>";
      total += price;
    }

  }
  //update total on website HTML
  document.getElementById("total").innerHTML = total.toFixed(2);
  //insert saved products to cart table
  document.getElementById("carttable").innerHTML = carttable;
  //update items in cart on website HTML
  document.getElementById("itemsquantity").innerHTML = items;
}
//user feedback on successful add
function addedToCart(pname) {
  var message = pname + " was added to the cart";
  var alerts = document.getElementById("alerts");
  alerts.innerHTML = message;
  if (!alerts.classList.contains("message")) {
    alerts.classList.add("message");
  }
}
/* User Manually empty cart */
function emptyCart() {
  //remove cart session storage object & refresh cart totals
  if (sessionStorage.getItem('cart')) {
    sessionStorage.removeItem('cart');
    updateCartTotal();
    //clear message and remove class style
    var alerts = document.getElementById("alerts");
    alerts.innerHTML = "";
    if (alerts.classList.contains("message")) {
      alerts.classList.remove("message");
    }
  }
}



$('.ticket-text').each(function() {
  var words = $(this).text().split(" ");
  var maxWords = 6;

  if (words.length > maxWords) {
    html = words.slice(0, maxWords) + '<span class="more_text" style="display:none;"> ' + words.slice(maxWords, words.length) + '</span>' + '<a href="#" class="read_more">...<br/>[Read More]</a>'

    $(this).html(html)

    $(this).find('a.read_more').click(function(event) {
      $(this).toggleClass("less");
      event.preventDefault();
      if ($(this).hasClass("less")) {
        $(this).html("<br/>[Read Less]")
        $(this).parent().find(".more_text").show();
      } else {
        $(this).html("...<br/>[Read More]")
        $(this).parent().find(".more_text").hide();
      }
    })

  }

})
@import url('https://fonts.googleapis.com/css?family=Quicksand:400,700');
*,
 ::before,
 ::after {
  box-sizing: border-box;
}

body {
  font-family: 'Quicksand', sans-serif;
  text-align: center;
  line-height: 1.5em;
  /*   background:#E0E4CC; */
  background: #69d2e7;
  background: -moz-linear-gradient(-45deg, #69d2e7 0%, #a7dbd8 25%, #e0e4cc 46%, #e0e4cc 54%, #f38630 75%, #fa6900 100%);
  background: -webkit-linear-gradient(-45deg, #69d2e7 0%, #a7dbd8 25%, #e0e4cc 46%, #e0e4cc 54%, #f38630 75%, #fa6900 100%);
  background: linear-gradient(135deg, #69d2e7 0%, #a7dbd8 25%, #e0e4cc 46%, #e0e4cc 54%, #f38630 75%, #fa6900 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#69d2e7', endColorstr='#fa6900', GradientType=1);
}

hr {
  border: none;
  background: #E0E4CC;
  height: 1px;
}

.container {
  max-width: 800px;
  margin: 1em auto;
  background: #FFF;
  padding: 30px;
  border-radius: 5px;
}

.productcont {
  display: grid;
}

.product {
  width: 310px;
  padding: 1em;
  border: 1px solid black;
  box-shadow: 0 0 5px 5PX rgba(229, 66, 64, 1);
  margin-right: 1em;
  border-radius: 5px;
}

.cart-container {
  border: 1px solid #E0E4CC;
  border-radius: 5px;
  margin-top: 1em;
  padding: 1em;
}

button,
input[type="submit"] {
  border: 1px solid #FA6900;
  color: #fff;
  background: #ed3330;
  padding: 0.6em 1em;
  font-size: 1em;
  line-height: 1;
  border-radius: 1.2em;
  transition: color 0.2s ease-in-out, background 0.2s ease-in-out, border-color 0.2s ease-in-out;
}

button:hover,
button:focus,
button:active,
input[type="submit"]:hover,
input[type="submit"]:focus,
input[type="submit"]:active {
  background: #0894fc;
  border-color: black;
  color: #000;
  cursor: pointer;
}

table {
  margin-bottom: 1em;
  border-collapse: collapse;
}

table td,
table th {
  text-align: left;
  padding: 0.25em 1em;
  border-bottom: 1px solid #E0E4CC;
}

#carttotals {
  margin-right: 0;
  margin-left: auto;
}

.cart-buttons {
  width: auto;
  margin-right: 0;
  margin-left: auto;
  display: flex;
  justify-content: flex-end;
  padding: 1em 0;
}

#emptycart {
  margin-right: 1em;
}

table td:nth-last-child(1) {
  text-align: right;
}

.message {
  border-width: 1px 0px;
  border-style: solid;
  border-color: #A7DBD8;
  color: #679996;
  padding: 0.5em 0;
  margin: 1em 0;
}

.ticket-text {
  text-align: center;
}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <h1>Course Packages</h1><br>
  <div id="alerts"></div>
  <div class="productcont">
    <div class="product">
      <h3 class="productname">product name</h3>
      <p><strong>Class :</strong></p>
      <p><strong>Board :</strong></p>
      <p><strong>Subject :</strong></p>
      <p class="ticket-text">Bacsaddsadsad on ipsum dolor amet se vsc sadsadasdd addasd sfsd sdfsdf</p>
      <span class="price amount">₹ 5.05</span>
      <del><span class="offered_price amount">₹ 1000</span></del><br></br>
      <button class="addtocart">Add To Cart</button>
      <button class="buynow ">Buy Now</button>
    </div>
  </div>

  <div class="cart-container">
    <h2>Cart</h2>
    <table>
      <thead>
        <tr>
          <th><strong>Product</strong></th>
          <th><strong>Price</strong></th>
        </tr>
      </thead>
      <tbody id="carttable">
      </tbody>
    </table>
    <hr>
    <table id="carttotals">
      <tr>
        <td><strong>Items</strong></td>
        <td><strong>Total</strong></td>
      </tr>
      <tr>
        <td>x <span id="itemsquantity">0</span></td>
        <td>₹<span id="total">0</span></td>
      </tr>
    </table>

    <div class="cart-buttons">
      <button id="emptycart">Empty Cart</button>
      <button id="checkout">Checkout</button>
    </div>
  </div>
</div>

2 个答案:

答案 0 :(得分:1)

在代码笔中,当您为元素分配多个类时,应使用classList检查类是否应用于该元素。

这是指向updated code

的链接
 while ((elem = elem.previousSibling)) {
    if (elem.nodeType === 3) continue; // text node
    if (elem.className == "price")
   // instead of using above condition use either
    if(elem.classList.contains('price'))
   // or
    if(elem.className === "price amount") 

    {
      getprice = elem.innerText;
    }
    if (elem.className == "productname") {
      getproductName = elem.innerText;
    }
    sibs.push(elem);
  }

答案 1 :(得分:0)

产品价格的

类名称不正确。检查此链接价格是否已添加

这是问题

consul validate common.json                             
Config validation failed: Error parsing common.json: 3 errors occurred:
    * invalid config key checks[0].script
    * invalid config key checks[1].script
    * invalid config key checks[2].script

更正如下: https://jsfiddle.net/h86cp4q2/

更改以下内容

1。

<span class="price amount">₹ 5.05</span>

收件人

<span class="price amount">₹ 5.05</span>

<span class="priceamount">₹ 5.05</span>

收件人

if(elem.className == "price"){

This shows the price of product