[英]Get object from array by clicked button id value Javascript, JQuery
我有一個包含來自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);
});
但是問題是它給了我來自phones數組的所有對象:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
您的grep
錯誤:
delegate
函數中的this
為您提供了對clicked元素的引用 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
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.