2010-05-26 158 views
2

這看起來像一個非常簡單的問題,但我不能得到它的工作。Javascript object key by element id? (jQuery)

我有一個Javascript對象是這樣的:

var person = {}; 
person.one = {gender: 'male', name: 'John'}; 
person.two = {gender: 'male', name: 'Doe'}; 
person.three = {gender: 'female', name: 'Jane'}; 

然後,我有一些HTML像這樣:

<a id="one">click</a> 
<a id="two">click</a> 
<a id="three">click</a> 

現在,我需要通過將點擊的ID來獲得正確的對象值鏈接。所以基本上,我需要動態訪問第一級對象鍵而無需for循環,因爲鍵是字符串。

我已經試過這樣:

$('a').click(function() { 
    alert(person[$(this).attr('id')['gender']]); 
}); 

它沒有工作。這也不是:

$('a').click(function() { 
    alert(person.($(this).attr('id')).gender); 
}); 

我回來的是一個「未捕獲的異常:語法錯誤,無法識別的表達式」。很明顯,我的語法是離開的。

我已經閱讀了很多文章,但找不到解決方案。有任何想法嗎?

+0

感謝球員,你是正確的!我很感激。 – bobsoap 2010-05-26 23:08:41

+0

你的第一個例子沒有奏效,因爲你把第一個右括號放在錯誤的地方。 '人[$(this).attr('id')] ['gender']' – seanmonstar 2010-05-26 23:10:58

回答

3

要使用動態域名就像你要訪問的屬性,正確的語法是用括號,就像一個數組。

alert(person[$(this).attr('id')].gender); 

或者,它可能只是清潔,尋找到該ID拉入一個單獨的變量:

var id = $(this).attr('id'); 
alert(person[id].gender); 

您的電話:)

+0

精彩:)非常感謝。我知道這是我的語法。 – bobsoap 2010-05-26 23:07:46

3

嘗試:

$('a').click(function() { 
    alert(person[$(this).attr('id')]['gender']); 
}); 

你有你的方括號在錯誤的地方。

2

嘗試alert(person[$(this).attr('id')].gender)