用js實現購物車自動計價功能

來源:互聯網
上載者:User

       當選擇修改資料後將自動計算每一個物品的的總價,並重新計算所有物品的總價.

因為沒有做太多相容性的東西,所以只在firefox下測試過.

DOM

 

<div>
   <table id="PriceTable">
     <thead><tr><td>物品編號</td><td>物品名稱</td><td >數量</td><td>價格</td><td>小計</td></tr></thead>
     <tbody>
        <tr><td >jsp_123</td><td >電腦</td><td><input type="text" value="1" /></td><td >1950</td><td >1950</td></tr>
        <tr><td >jsp_123</td><td >電腦</td><td><input type="text" value="1" /></td><td >1950</td><td>1950</td></tr>
        <tr><td >jsp_123</td><td >電腦</td><td><input type="text" value="1" /></td><td >1950</td><td >1950</td></tr>
        <tr><td>jsp_123</td><td>電腦</td><td><input type="text" value="1" /></td><td>1950</td><td>1950</td></tr>
     </tbody>
     <tfoot>
       <tr><td>總計:</td><td colspan="4">7800</td></tr>
     </tfoot>
   </table>
</div>
<input type="button"   onclick="GetInAll()" value="計算" />

 

JS:

 

    <title>購物車自動計價</title>
    <script type="text/javascript" src="misc/jquery.min.js"></script>
    <script type="text/javascript">
    $(function(){
    $("table input").blur(function(oEven){
    
     var num=oEven.target.parentNode.parentNode.cells[2].firstChild.value;
     var price=oEven.target.parentNode.parentNode.cells[3].textContent;
     var count=parseFloat(num)*parseFloat(price);//計算單個物品價格

    oEven.target.parentNode.parentNode.cells[4].textContent=count;
    GetInAll();//計算所有物品價格
    });
    })
   
    function GetInAll()
    {
    var table=document.getElementById("PriceTable");
    var oBody=table.tBodies[0];
    var oFoot=table.tFoot;
   
    var rows=oBody.rows;
    var priceCount=0;
   
    for(var i=0;i<rows.length;i++)
    {
     var tempData=rows[i].cells[4].textContent;
     priceCount=parseFloat(priceCount)+parseFloat(tempData);

    }
    alert(priceCount);
    oFoot.rows[0].cells[1].textContent=priceCount;
    
    }
    </script>

    <style type="text/css">
     table input[type=text]{ width:32px;}
    </style>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.