jQuery:忘记DOM结构,只需找到此类的下一个元素 [英] Jquery: Forget the DOM structure, just find the next element with this class

查看:85
本文介绍了jQuery:忘记DOM结构,只需找到此类的下一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得以前已经问过这个问题,但答案似乎对每个海报都非常具体.

I feel like this question has been asked before but the answers seem pretty specific to each poster.

我正在寻找一种识别给定元素并找到具有特定类的下一个元素的方法.我不想处理parent()或children(),因为我正在解析一个表,并且我不希望它停在一行的末尾甚至是表本身的末尾(有是两个并排的.

I'm looking for a way to identify a given element and find the next element that has a particular class. I don't want to have to deal with parent() or children() since I'm parsing through a table and I don't want it to stop at the end of a row or even the end of the table itself (there are two side-by-side).

有什么方法可以在整个页面中搜索元素的下一个实例吗?

Is there any way to just search the entire page for the next instance of an element?

背景信息: http://jsfiddle.net/HKkAa/2/

我正在尝试从突出显示的单元格开始遍历底部表格,并将突出显示"类应用于每个单元格,直到达到结束日期为止.我有一种计算结束日期的方法,我只需要魔术方法即可选择链接的下一个实例.

I'm trying to iterate through the bottom table starting at the highlighted cell and applying the "highlight" class to each cell until I reach the end date. I have a way to calculate when I've reached the end date, I just need the magic method to select the next instance of a link.

推荐答案

编辑

对于任何有兴趣的人,我在这里对此进行了插件验证: https://github.com/techfoobar/jquery-next-in-dom

For anyone interested, I've plugin-ified this here: https://github.com/techfoobar/jquery-next-in-dom

如果您希望它是完全通用的并且能够满足所有/任何DOM结构,则jQuery中没有内置的方法.我曾经设计出一个简单的递归函数来做到这一点.就像这样:

There is no built-in way of doing this in jQuery if you want it to be completely generic and able to satisfy all/any DOM structure. I once worked out a simple recursive function that does this. It goes like:

function nextInDOM(_selector, _subject) {
    var next = getNext(_subject);
    while(next.length != 0) {
        var found = searchFor(_selector, next);
        if(found != null) return found;
        next = getNext(next);
    }
    return null;
}
function getNext(_subject) {
    if(_subject.next().length > 0) return _subject.next();
    return getNext(_subject.parent());
}
function searchFor(_selector, _subject) {
    if(_subject.is(_selector)) return _subject;
    else {
        var found = null;
        _subject.children().each(function() {
            found = searchFor(_selector, $(this));
            if(found != null) return false;
        });
        return found;
    }
    return null; // will/should never get here
}

您可以这样称呼它:

nextInDOM('selector-to-match', element-to-start-searching-from-but-not-inclusive);

例如:

var nextInst = nextInDOM('.foo', $('#item'));

无论DOM结构如何,都会在$('#item')之后为您提供第一个匹配的.foo

will get you the first matching .foo after $('#item') regardless of the DOM structure

在此处检查原始答案: https://stackoverflow.com/a/11560428/921204

Check the original answer here: https://stackoverflow.com/a/11560428/921204

这篇关于jQuery:忘记DOM结构,只需找到此类的下一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆