gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:17:59 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com