我有一个包含json数据的手机数组:
var phones = [
{
"age": 0,
"id": "motorola-xoom-with-wi-fi",
"imageUrl": "img/phones/motorola-xoom-with-wi-fi.0.jpg",
"name": "Motorola XOOM\u2122 with Wi-Fi",
"snippet": "The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM with Wi-Fi, the world's first tablet powered by Android 3.0 (Honeycomb).",
"price": 150
},
它通过此模板显示为ul li:
<script type="text/template" id="listTemplate">
<ul id = "list">
<% for (var i=0; i< phones.length; i++) { %>
<li><%=phones[i].age %><br>
<%=phones[i].name%><br>
<%=phones[i].id%><br>
<img src="<%=phones[i].imageUrl%>"/><br>
<%=phones[i].snippet%><br>
<p>Price: <%=phones[i].price%></p>
<button id="<%=phones[i].id%>" class="btn btn-success" type="submit">Buy</button>
</li>
<% } %>
</ul>
</script>
此模板将按钮ID设置为手机的ID。通过按下这个按钮我想从手机阵列获得“id”,“name”和“price”。为了实现这一点,我写了这段代码:
$("#list").delegate("button",'click',function(){
var purchase = $.grep(phones, function () {
return this.id === phones.id;
});
console.log(purchase);
});
但问题是它给了我来自手机阵列的所有对象:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
答案 0 :(得分:0)
您的grep
错了:
this
函数中的delegate
为您提供了对点击元素的引用phones
对象数组进行比较后phone
$("#list").delegate("button",'click',function(){
var purchase = $.grep(phones, function(current){
console.info(current); // gives you phones one by one
return current.id===this.id; // return only clicked one
});
console.log(purchase); // only array of clicked items
console.log(purchase[0]); // phone with same id
console.log(this); // clicked item
});