正在根据ID从数组中检索对象

Retrieving object from array based on ID

本文关键字:数组 检索 对象 ID      更新时间:2023-09-26

我有一个包含对象(列表项)的数组(myElems)。我想从这个数组中找出一个ID匹配"foo"的元素。"foo"字符串当前存储在var"targetItem"中最后,我需要获取匹配元素的位置。顶部

var targetItem = 'foo'; // value of this var is set dynamically
$(myElems).grep(function(ele){
retun ele.id == menuItem;
});
var loc = // [returned from array].position.top;

是的,我知道这是大杂烩。。。我不知道如何语法这个

感谢

编辑:创建myElems

var myElems = [];
    $('#menu').children('li').each(function() {
        myElems.push( $(this) ); 
    });

html:

<ul id="menu">
    <li id="foo">FOO ITEM</li>
    <li id="boo">BOO ITEM</li>
</ul>

JS

var ele = $('#foo').attr('id')
var myElems = [];
$('#menu').children('li').each(function() {
    myElems.push( $(this).attr('id') ); 
});
var targetItem = 'foo'; // value of this var is set dynamically
var newelement =  $.grep(myElems, function( ele, i ){
                      return ele == targetItem ;
                     //console.log("This is the position of matched item - ", + i);
                   });

Fiddle:http://jsfiddle.net/Xt6Wh/2/

检查ele.id是否获得所需的值。在小提琴中,我从div中获取值——只是为了表明逻辑是有效的。我不确定你从哪里得到ele.id。因此,我接受了这个假设。

我能想到的最好的方法是在数组上迭代,然后使用grep

$.grep(myElems,function(value,id){
    return id == targetItem;
});

如果这对你有效,请告诉我,否则我会根据你的评论编辑我的答案。这是我能给你的最好的代码。

在香草js中。

el = myElems.filter(function (elem) {
    return elem["id"] == "foo";
})

这将获得一个匹配"foo"的元素数组。然后你可以检查一下你是否有什么东西:

if(el.length > 0) el = el[0]
// To get the correct element you can just stick to CSS id selector:
var target = $('#menu').children('li#' + targetItem);
// to get the CSS top value you can do
var top = target.css("top");

当然,如果存在不存在目标元素的情况,则可以检查target.length

http://jsfiddle.net/jeVSJ/