我有一些 json 和 jQuery 似乎没有正确选择它的元素。我引用的 json 文档可在此处找到:http://pastebin.com/bM3BvD2F。
json 是一组元素,我正在尝试选择一个具有所需 ID 的元素。
(您可以复制粘贴到 http://jsonviewer.stack.hu/ 以获得漂亮的折叠 View )
这是我遇到问题的代码:
//get current picture ID - will return '2' - correct value
var currentID = window.location.hash ? window.location.hash.substring(1) : allImages[0]["id"];
//this line will alert name attribute value for a picture with (id = 4) - wrong :(
alert($(allImages[id=currentID])[0].name);
最佳答案
allImages
是一个普通数组,因此 allImages[id=currentID]
将导致创建名为 id
的临时变量,并为其赋值currentID
并返回 2,导致返回数组中的第三个元素。该元素的 id
确实为 4。
您需要的是“深度搜索”,实现此目的的一种方法是使用 .map
函数:
var name = jQuery.map(allImages, function (value) {
return (value.id == currentID) ? value : null;
})[0].name;
快速测试用例:http://jsfiddle.net/PWPcE/
关于javascript - 使用 jQuery 选择器选择 JavaScript 数组元素项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5528968/