[英]Get object from array by clicked button id value Javascript, JQuery
I have a phones array that contains data from json: 我有一个包含来自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
},
It displays as a ul li by this template: 该模板显示为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>
This template sets button id to id of the phone. 此模板将按钮ID设置为电话的ID。 By cliking this button I want to get "id", "name" and "price" from phones array. 通过单击此按钮,我想从电话阵列中获取“ id”,“ name”和“ price”。 To achive this I wrote this code: 为了达到这个目的,我编写了以下代码:
$("#list").delegate("button",'click',function(){
var purchase = $.grep(phones, function () {
return this.id === phones.id;
});
console.log(purchase);
});
But problem is that it gives me all objects from phones array: 但是问题是它给了我来自phones数组的所有对象:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
Your grep
is wrong: 您的grep
错误:
this
in the delegate
function gives you a reference to clicked element delegate
函数中的this
为您提供了对clicked元素的引用 phones
array of objects 与现有phones
对象数组比较之后 phone
with a correct ID grep之后,只有具有正确ID的特定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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.