javascript - 使用 jQuery 选择器选择 JavaScript 数组元素项

标签 javascript jquery jquery-selectors

我有一些 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/

相关文章:

javascript - 循环内的嵌套 ajax 调用未按顺序执行

按键上的 Javascript 仅触发一次

javascript - 如何随机停止超时功能

Javascript Loop 不显示超过 1 个数据实例

javascript - JEdi​​table 返回不正确的响应

jquery - 隐藏显示切换按钮图像

javascript - 多次下拉选择后更新页面部分

javascript - 如何使用 jQuery 检查选​​择/单击的元素是否是 "n"的倍数?

jquery - 结合jQuery :not and :nth-child selectors

jQuery - 选择不包含在另一个类中的类