2012-04-06 90 views
2

我在我的網站上有一個購物車,我需要讓用戶輕鬆地更改他們在購物車中的物品數量。使用jQuery和一些輸入創建一個鍵/對象

下面是javascript代碼我到目前爲止:

<script type="text/javascript" language="javascript"> 
    $(document).ready(function() { 

     var items = []; 

     $(".item").each(function() { 
      var productKey = $(this).find("input[type='hidden']").val(); 
      var productQuantity = $(this).find("input[type='text']").val(); 
      items.addKey(productKey, productQuantity); ? 
     }); 

     // 1. Grab the values of each ammount input and it's productId. 

     // 2. Send this dictionary of key pairs to a JSON action method. 

     // 3. If results are OK, reload this page. 
    }); 
</script> 

我寫的評論是我對如何進行公正的準則。

有沒有辦法將一個鍵/對元素添加到一個排序數組?我只需要它有一個關鍵和價值。沒有什麼花哨。

我寫了一個addKey()方法只是爲了說明的目的,以顯示我想完成。

回答

4
items[productKey] = productQuantity; 
0

您可以匿名對象添加到項目陣列,如:

items.push({ 
    key: productKey, 
    quantity: productQuantity 
}); 

再後來訪問它們作爲items[0].keyitems[0].quantity

0

你也可以使用JQuery.data方法,就像你也可以擺脫那些隱藏的。

1

在JavaScript中,數組是對象(typeof(new Array)==='object'),以及對象可以具有可以獲取/設置使用點狀或括號,即語法屬性:

var a = [1,2,3]; 
JSON.stringify(a); // => "[1,2,3]" 
a.foo = 'Foo'; 
a.foo; // => 'Foo' 
a['foo']; // => 'Foo' 
JSON.stringify(a); // => "[1,2,3]" 

所以你的情況,你可以簡單的產品數量值排列爲item陣列的productKey屬性,因此:

items[productKey] = productQuantity; 
items[productKey]; // => productQuantity