最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript object key by element id? (jQuery) - Stack Overflow

programmeradmin2浏览0评论

This looks like a very simple issue, but I just can't get it to work.

I have a Javascript object like this:

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

Then I have some HTML like so:

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

Now, I need to get the correct object value by the id of the clicked link. So basically, I need to dynamically access the 1st-level object keys without a for-loop, since the keys are strings.

I've tried this:

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

It didn't work. Neither did this:

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

All I get back is an "uncaught exception: Syntax error, unrecognized expression". Obviously, my syntax is way off.

I've already read through many posts on here, but couldn't find the solution. Any ideas?

This looks like a very simple issue, but I just can't get it to work.

I have a Javascript object like this:

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

Then I have some HTML like so:

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

Now, I need to get the correct object value by the id of the clicked link. So basically, I need to dynamically access the 1st-level object keys without a for-loop, since the keys are strings.

I've tried this:

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

It didn't work. Neither did this:

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

All I get back is an "uncaught exception: Syntax error, unrecognized expression". Obviously, my syntax is way off.

I've already read through many posts on here, but couldn't find the solution. Any ideas?

Share Improve this question asked May 26, 2010 at 22:48 bobsoapbobsoap 5,1347 gold badges32 silver badges43 bronze badges 1
  • your first example didnt work because you put the first closing brace in the wrong place. person[$(this).attr('id')]['gender'] – seanmonstar Commented May 26, 2010 at 23:10
Add a ment  | 

3 Answers 3

Reset to default 3

To access a property with a dynamic name like you're going for, the correct syntax is to use brackets, like an array.

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

Or it might just be cleaner-looking to pull that ID into a separate variable:

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

Your call :)

Try:

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

You had your square brackets in the wrong spot.

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

发布评论

评论列表(0)

  1. 暂无评论