在纯JavaScript中自动计算数据属性的总和

时间:2015-08-14 12:04:01

标签: javascript html attributes sum

我已经尝试了很长时间,在向购物篮添加/删除内容时自动计算数据属性的总和,并计算纯JavaScript中没有Jquery的数据属性总数而无法修复它!我是JavaScript新手......

这是我的代码:

HTML: //购物篮部分

<div id="basket">Shopping Basket</div>
    <ul class="cart" id="cart_id">
    </ul>

    <form>
        <br>Total Price:
        <input type="text" name="totalPrice" id="totalPrice" value="&euro; 0" disabled> 
    </form>
<div>

//类别选择部分

 <ul class="products" id="product_id">
     <li class="cat" id="cat_id" name="data" data-title="iPad" data-price="299">iPad (&euro;299)<img class="plusicon" src="plusicon.jpg" alt="plusicon"/></li>
     <li class="cat" id="cat_id"  name="data" data-title="iPad Air" data-price="399">Ipad Air (&euro;399)<img class="plusicon" src="plusicon.jpg" alt="plusicon"/></li>
     <li class="cat" id="cat_id"  name="data" data-title="Sony Xperia Z2" data-price="399">Sony Xperia Z2 (&euro;399)<img class="plusicon" src="plusicon.jpg" alt="plusicon"/></li>
     <li class="cat" id="cat_id"  name="data" data-title="Samsung Galaxy Tab 10,1" data-price="349">Samsung Galaxy Tab 10,1 (&euro;349)<img class="plusicon" src="plusicon.jpg" alt="plusicon"/></li>

</ul>

JS:

function init(){
    plus = [].slice.call(document.querySelectorAll(".plusicon"), 0);
    for (var i = 0; i < plus.length; i++) {
        plus[i].addEventListener("click", addToBasasket, false);
    }
}

function addToBasket (e) {

    e.stopPropagation();

    var ele = info[plus.indexOf(this)];

    var title = ele.getAttribute("data-title");

    var price = parseInt(ele.getAttribute("data-price"));

    var ul = document.getElementById("cart_id");

    var li = document.createElement("li");  

    var remove = document.createElement("img");

    remove.className = "removeicon";
    remove.src = "removeicon.jpg";

    remove.addEventListener("click", removeThingFromList, false);
    li.appendChild(remove);
    li.appendChild(document.createTextNode(title+" (\u20AC"+price+")"));    
    ul.appendChild(li);

    //So when you press "plusicon" it adds to shopping basket and when you press "removeicon" it deletes from the basket!

    //Here below is my problem, I have tried for so long but I cant get to work
    //to show the total price when adding and removing li to basket!

    var total = 0;

    listItem = ele.getAttribute("data-price");

    for (var i=0; i < listItem.length; i++) 
    { 
        total += parseInt(ele.getAttribute("data-price")); 
    }

    document.querySelector("#totalPrice").value = total;
    //I have tried so many different ways but can't get it to work the total of attribute("data-price")!


    //This functions below works and removes the current li

    function removeThingFromList(e){
        this.parentNode.parentNode.removeChild(this.parentNode);
    }
}

我希望有人可以提供帮助!提前谢谢!

2 个答案:

答案 0 :(得分:2)

您必须将价格存储在添加到购物篮中的新商品(li)的某些属性中:

li.appendChild(remove);
//Storing price in data-price attribute
li.setAttribute("data-price", price); 
li.appendChild(document.createTextNode(title+" (\u20AC"+price+")"));   
ul.appendChild(li);

之后,您可以获取此属性并计算总数:

var total = 0;
var listItem = document.getElementById("cart_id").getElementsByTagName("li");

for (var i=0; i < listItem.length; i++) 
{ 
    total += parseInt(listItem[i].getAttribute("data-price")); 
}

答案 1 :(得分:0)

<ul>
  <li class="cart_item" data-prize="12.6" data-id="5">Hello €12.6</li>
  <li class="cart_item" data-prize="4.25" data-id="8">World €4.25</li>
  <li class="cart_item" data-prize="13.8" data-id="9">Foo €13.8</li>
  <li class="cart_item" data-prize="6.3" data-id="12">Bar €6.3</li>
</ul>
<input type="button" value="TOTAL" onclick="calculateTotal();">
<div id="messages"></div>

<script>
  function data(elm, key) {
    for(var i in elm.attributes) {
      if ( elm.attributes[i].name.substr(0, 5) === 'data-' ) {  // checks if the 5 first letters of the attribute are 'data-'
        // it's a data- attribute.  Now let's see if it's the right one
        if ( elm.attributes[i].name.substr(5) === key) {  // checks if the letters, next to the 5 first letters, correspond with the key we need
          return elm.attributes[i].value;
        }
      }
    }
    return '';
  }

  function calculateTotal() {
    document.getElementById("messages").innerHTML = '';
    var items = document.getElementsByClassName("cart_item");
    var sum=0;
    for (var i in items) {
      var prize = Number( data(items[i], 'prize') );  // without the Number(), it's seen as text
      sum += prize;
      if(prize) {  // else it also shows blank lines
        document.getElementById("messages").innerHTML += prize + '<br>';
      }
    }
    document.getElementById("messages").innerHTML += '+ -----<br>' + sum;
  }
</script>