通过点击的按钮id值Javascript,JQuery

时间:2015-05-20 10:20:49

标签: 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",
            "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

1 个答案:

答案 0 :(得分:0)

您的grep错了:

    this函数中的
  • delegate为您提供了对点击元素的引用
  • 与现有的phones对象数组进行比较后
  • 在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

});