1

我在一页上有 50 个点,每个单独的 div。当我单击一个时,我想使用 ID 从数组中提取值。我可以获得 ID,但我无法使用该值从我的数组中取出东西。也许是全局变量问题?没有把握。甚至不确定这是否是处理访问多个数据的多次点击的最佳方式。任何帮助表示赞赏!

var location0 = {"name" : "Location 1", "image" : "image1.jpg"};

$('.dot').click(function(){
    var thisLocation = $(this).attr("id");
    alert(thisLocation); //Returns "location0"
    alert(thisLocation["image"]); //Returns "undefined"
});

这是一个小提琴。

4

3 回答 3

5

我会这样做:

var locations = {
    location1 : {"name" : "Location 1", "image" : "image1.jpg"},
    location2 : {"name" : "Location 2", "image" : "image2.jpg"}
}

$('.dot').click(function(){
    alert(locations[this.id].name);
});
​

小提琴

于 2012-12-12T21:07:48.450 回答
2

$(this).attr("id")返回一个字符串"location0"。如果你想使用它,你必须得到一个实际的location0变量,所以你必须使用eval()函数替换你的代码行之一。像这样:

var thisLocation = eval($(this).attr("id"));

但是,我建议使用一个新数组,其中"location0"将是一个键,那么您只需要使用类似字符串访问一个键locations["location0"]并避免使用eval().

于 2012-12-12T21:11:10.090 回答
0

你需要像这样访问它:

var test = {
    location0:    {"name" : "Location 1", "image" : "image1.jpg"}
};


$('.dot').click(function(){
    var thisLocation = $(this).attr("id");
    alert(thisLocation); //Returns "location0"
    alert(test[thisLocation]["image"]); //Returns "undefined"
});

​</p>

编辑:这有效

另外它首先对您不起作用的原因是因为 thisLocation 是一个字符串,而不是它自己的对象,因此您需要使用括号通过传递名称来访问对象属性。我只是不建议

于 2012-12-12T21:02:52.283 回答