我正在尝试使用HTML中某些文本的值访问我的派对象。
但是,代码使用的是变量名,而不是变量的值。
对我来说,这似乎应该很明显,但这让我感到困惑。
谢谢
var pie = {
welfare: {
title: "Welfare",
percentage : 24,
point: 0,
color: '#601C6B'
},
health: {
title: "Health",
percentage : 20,
point: 0,
color: '#FFAA97'
},
state_pensions: {
title: "State pensions",
percentage : 13,
point: 0,
color: "#9C9C9C"
}
}
$('.pie_item').click(function(){
var pie_piece = $(this).text();
console.log("this is " + pie_piece);
$(this).closest(".drop_down_button").find('p').text(pie_piece);
console.log(pie.pie_piece);
});
答案 0 :(得分:2)
在对象pie.pie_piece
上使用点表示法进行属性访问时,它将在pie_piece
对象中查找实际名称为pie
的属性。
要使用pie_piece
的值,您将要使用方括号表示法
pie[pie_piece]
有关property access的更多信息
答案 1 :(得分:0)
您可以使用符号object['element']
访问对象的元素。因此,在这种情况下,如果pie_piece是pie[pie_piece]
,welfare
或health
,则可以执行state_pensions
之类的事情。
var pie = {
welfare: {
title: "Welfare",
percentage : 24,
point: 0,
color: '#601C6B'
},
health: {
title: "Health",
percentage : 20,
point: 0,
color: '#FFAA97'
},
state_pensions: {
title: "State pensions",
percentage : 13,
point: 0,
color: "#9C9C9C"
}
}
$('.pie_item').click(function(){
var pie_piece = $(this).text();
console.log("this is " + pie_piece);
$(this).closest(".drop_down_button").find('p').text(pie_piece);
console.log(pie[pie_piece]);
});