通过单击按钮id值Javascript、JQuery从数组中获取对象

通过单击按钮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",

我有一个电话阵列,其中包含来自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> 
但问题是它提供了来自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

});