Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript对象键(按元素id)?(jQuery)_Javascript_Jquery - Fatal编程技术网

Javascript对象键(按元素id)?(jQuery)

Javascript对象键(按元素id)?(jQuery),javascript,jquery,Javascript,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</

这看起来是一个非常简单的问题,但我就是不能让它工作

我有一个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>
它不起作用。这也没有:

$('a').click(function() {
   alert(person.($(this).attr('id')).gender);
});
我得到的只是一个“未捕获的异常:语法错误,无法识别的表达式”。显然,我的语法有点不对劲

我已经阅读了很多关于这里的帖子,但是找不到解决方案。有什么想法吗?

试试:

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

您的方括号放错了位置。

请尝试
警报(person[$(this).attr('id')].gender)
要访问具有动态名称的属性,正确的语法是使用括号,如数组

alert(person[$(this).attr('id')].gender);
或者,将该ID拉入一个单独的变量可能会更干净:

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

你的电话:)

谢谢各位,你们都说对了!我很感激。你的第一个例子不起作用,因为你把第一个右括号放错地方了<代码>人物[$(this).attr('id')]['gender']
var id = $(this).attr('id');
alert(person[id].gender);