通过单击按钮id值Javascript、JQuery从数组中获取对象
我有一个电话阵列,其中包含来自json的数据:通过单击按钮id值Javascript、JQuery从数组中获取对象,javascript,jquery,javascript-events,Javascript,Jquery,Javascript Events,我有一个电话阵列,其中包含来自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",
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>
但问题是它提供了来自phones阵列的所有对象:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
您的
grep
错误:
在此
函数中提供对单击元素的引用委托
- 与现有的
对象数组进行比较后手机
- 在grep之后,只有特定的
具有正确的ID电话
什么是
phones.id
这里this.id===phones.id
phones
只是一个对象数组,您可以使用其索引逐个访问其对象。它没有名为id
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
$("#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
});