这看起来像一个非常简单的问题,但我不能得到它的工作。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);
});
我回来的是一个“未捕获的异常:语法错误,无法识别的表达式”。很明显,我的语法是离开的。
我已经阅读了很多文章,但找不到解决方案。有任何想法吗?
感谢球员,你是正确的!我很感激。 – bobsoap 2010-05-26 23:08:41
你的第一个例子没有奏效,因为你把第一个右括号放在错误的地方。 '人[$(this).attr('id')] ['gender']' – seanmonstar 2010-05-26 23:10:58