如何给多个按钮设置和获取ID

        我用tmpl模板动态生成商品列表,其中用一列添加按钮模板动态生成很多“加入购物车”按钮,当点击该按钮商品会加入购物车,这就需要给这些按钮添加ID,通过ID找到相应的商品信息加入到购物车,具体内容如下:

//以下是写在html <head>标签中的tmpl模板:
<script  type="text/x-jquery-tmpl"  id="trPemp">
     <tr>
         <td >${classification}</td>
         <td >${name}</td>
         <td >${price}</td>
         <td >${unit}</td>
         <td ><button   id=${id}  >加入购物车</button></td> //生成按钮模板
     </tr>
</script>

   

// 给多个按钮添加ID  
var cartList = [
    {classification: "饮料",name: "可口可乐", price: "3", unit: "瓶" ,id:"1"},
    {classification: "饮料",name: "雪碧", price : "3",   unit: "瓶",id:"2"},
    {classification: "水果", name: "苹果", price : "5.5", unit: "斤",id:"3"},
    {classification: "水果", name: "荔枝",  price: "15",   unit: "斤",id:"4"},
    {classification: "生活用品",name: "电池", price : "2", unit: "个",id:"5"},
    {classification: "食品", name: "方便面",  price: "4.5", unit: "袋",id:"6"}
]
//通过tmpl方法在id为tableLis的表格中生成的5个按钮,有了不同的ID
 $("#trPemp").tmpl(cartList).appendTo('#tableList');
//给这些按钮添加点击事件,当点击某商品的“加入购物车”按钮时通过获取该按钮的ID就可以找到该商品的信息并将其添加到从本地取出的数组中然后再存回到本地,以供购物车页面获取它
function addClickEvent(){
    var data=JSON.parse(localStorage.getItem("data"))||[];
    $("button").click( function(){
    data.push(cartList [ this.id ] );    //this.id  为获取点击按钮的ID       
     localStorage.setItem("data",JSON.stringify(data));
      })
 }
 

猜你喜欢

转载自2806814127.iteye.com/blog/2314850