选择正确的itemID jQuery

时间:2018-11-29 07:31:07

标签: jquery html

我附加了此字符串,列出了mycart.html中的项目

 t = "<div class='items'><img src='"+ serverURL() + "/images/" + 
arr[i].itemImage + "' class='image'><div class='deletebtn'><input 
type='image' id='deletebtn' src='images/deletebtn.jpg' class='deletebtn'> 
</div><div class='itemName'><b> "+arr[i].itemName+"</b></div> <div 
class='itemID'>Item ID : " +arr[i].itemID+" </div><div class='itemSize'> 
<b>"+ arr[i].itemSize+"</b></div><div class='itemPrice'>$"+ 
arr[i].itemPrice +"</div></div>"

我的目的是如果单击“删除”,则删除该项目。如何获取正确的itemID,以便能够将值转移到json对象?

 function deleteitem(){

    var url = serverURL() + "/deletemycartitems.php";
    var  email = localStorage.getItem("email");
   //var itemID = ;
  var JSONObject = {
    "email": email,
    "itemID": itemID,

  };

  $.ajax({
   url: url,
   type: 'GET',
   data: JSONObject,
   dataType:'json',
   contentType: "application/json; charset=utf-8",
   success: function (arr) {
  _getmycart(arr);
  },
  error: function () {
   alert("Failed");
  }
});


}

2 个答案:

答案 0 :(得分:0)

尝试一下

t="<div class='items'>"+
       "<img src='"+ serverURL() + "/images/" + arr[i].itemImage + "' class='image'>"+
       "<div class='deletebtn'>"+
           "<button onclick='deleteitem("+arr[i].itemID+")'>Delete</button>"+ 
       "</div>"+
       "<div class='itemName'><b> "+arr[i].itemName+"</b></div>"+
       "<div class='itemID'>Item ID : " +arr[i].itemID+" </div>"+
       "<div class='itemSize'> <b>"+ arr[i].itemSize+"</b></div>"+
       "<div class='itemPrice'>$"+ arr[i].itemPrice +"</div>"+
  "</div>"

并在

中获取参数
function deleteitem(itemId){
    ...
}

现在您可以在函数中使用商品ID。

答案 1 :(得分:0)

您需要将itemid作为数据项存储在按钮中

<input 
type='image' id='deletebtn' src='images/deletebtn.jpg' class='deletebtn' data-itemid='"+arr[i].itemID+"'> 

然后单击“删除”按钮,只需尝试将该ID检索为

let itemId = $(this).data('itemid');