2011-08-18 57 views
0

例如,我有JavaScript數組是這樣的:現在如何使用jQuery像這樣從數組中返回數據?

var data = [ 
{text:'Business', aid:'6'}, 
{text:'Careers', aid:'29'}, 
{text:'Credits', aid:'28'}, 
{text:'Insurance', aid:'30'} 
]; 

,在URL傳遞ID,我需要搶基於該ID像這陣「文」:

$('#category').val(data, function(item) {return item.aid['6'].text;}); // = Business 

所以我想根據傳遞的URL ID = aid來填充表單字段#category中來自數組的文本?

在此先感謝

回答

1

使用filter[MDN]方法來獲得正確的對象:

var aid = 28, 
    match = data.filter(function(elem) { return elem.aid == aid; }); 

if (match.length) { 
    $('#category').val(match[0].text); 
} 
+0

十分感謝:) – Bobo

+0

嗨@FishBasketGordo剛剛發現,IE8使得錯誤,如: 「消息:對象不支持此屬性或方法」。你能建議我該怎麼做?謝謝 – Bobo

+0

找到的解決方案,只是更改爲: match = $ .grep(data,function(elem){return elem.aid == aid;}); – Bobo