检查元素是在 jQuery 中的另一个元素之前还是之后

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7208624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:32:58  来源:igfitidea点击:

Check if element is before or after another element in jQuery

jquerydom

提问by Peter Olson

Let us suppose I have this markup

让我们假设我有这个标记

<h3 id="first">First</h3>
<p>Hi</p>
<p>Hello</p>
<h3 id="second">Second</h3>
<p>Bye</p>
<p>Goodbye</p>

How can I programmatically check if an element, such as one of the ps, is after first h3and before the second h3, with jQuery?

如何使用 jQuery 以编程方式检查元素(例如ps 中的一个)是否在 first 之后h3和 second 之前h3

I am trying to do something like this:

我正在尝试做这样的事情:

$(p).each(function(){
   if($(this).isAfter("#first") && $(this).isBefore("#second")) {
     // do stuff
   }
});

回答by Marco Fucci

Rocket's solution works fine if selis a real selector, if you pass a jquery object though, it won't work.

如果sel是一个真正的选择器,Rocket 的解决方案就可以正常工作,但是如果您传递一个 jquery 对象,它将不起作用。

If you want a plugin that works with both selectors and jquery objects, just use my slightly modified version instead:

如果你想要一个可以同时使用选择器和 jquery 对象的插件,只需使用我稍微修改过的版本:

(function($) {
    $.fn.isAfter = function(sel){
        return this.prevAll().filter(sel).length !== 0;
    };

    $.fn.isBefore= function(sel){
        return this.nextAll().filter(sel).length !== 0;
    };
})(jQuery);

Kudos to Rocket for the original solution.

感谢 Rocket 的原始解决方案。

回答by Rocket Hazmat

To see if an element is after another, you can use prev()or prevAll()to get the previous element(s), and see if it matches.

要查看一个元素是否在另一个元素之后,您可以使用prev()prevAll()获取前一个元素,并查看它是否匹配。

And to see if an element is before another, you can use next()or nextAll()to get the next element(s), and see if it matches.

并查看一个元素是否在另一个元素之前,您可以使用next()nextAll()获取下一个元素,并查看它是否匹配。

$.fn.isAfter = function(sel){
  return this.prevAll(sel).length !== 0;
}
$.fn.isBefore= function(sel){
  return this.nextAll(sel).length !== 0;
}

DEMO: http://jsfiddle.net/bk4k7/

演示:http: //jsfiddle.net/bk4k7/

回答by Dennis

You can use the index()function:

您可以使用该index()功能:

$('p').each(function(){
   var index = $(this).index();
   if(index > $("#first").index() && index < $("#second").index()) {
     // do stuff
   }
});

回答by Amin Eshaq

Here is a fiddle

这是一个小提琴

$('p').each(function() {
    previousH3 = $(this).prevAll('h3');
    nextH3 = $(this).nextAll('h3');

    if (previousH3.length > 0 && nextH3.length > 0) {
        $(this).css('color', 'red')
    }

});

回答by Arash Dalir

I implemented a general isAfterfunction, which considers the depth and DOM tree and can correctly determine if ais after beven if they are in 2 different subtrees:

我实现了一个通用isAfter函数,它考虑了深度和 DOM 树,即使它们位于 2 个不同的子树中,也可以正确确定是否a在之后b

<div>
  <div>
    <p class="first">I come first</p>
  </div>
</div>

<div>
  <div>
    <p class="second">I come second</p>
  </div>
</div>

you can find it in my GitHub Repository. Would appreciate your feedback on the code

你可以在我的 GitHub Repository 中找到它。感谢您对代码的反馈

回答by Peter

The answer:

答案:

$.fn.isAfter = function(sel){
    return this.prevAll(sel).length !== 0;
}
$.fn.isBefore= function(sel){
    return this.nextAll(sel).length !== 0;
}

Was selecting all previous elements or next elements regardless of the selector (sel) so I made the following modifications that select elements based on class:

无论选择器(sel)如何选择所有上一个元素或下一个元素,所以我进行了以下修改,根据类选择元素:

$.fn.isAfter = function(sel){
    sel = "." + sel.attr("class").replace(/ /g, ".");

    return this.prevAll(sel).length !== 0;
}
$.fn.isBefore= function(sel){
    sel = "." + sel.attr("class").replace(/ /g, ".");

    return this.nextAll(sel).length !== 0;
}

回答by Joe

The accepted answer only works if the elements are at the same level. One approach to solve it if you want to locate which element is first regardless of the level is:

接受的答案仅在元素处于同一级别时才有效。如果您想在不考虑级别的情况下首先定位哪个元素,则解决此问题的一种方法是:

  1. Set a temporary attribute to each element with the same value
  2. Use a jquery selector to locate the first element with that attribute value
  1. 为每个具有相同值的元素设置一个临时属性
  2. 使用 jquery 选择器定位具有该属性值的第一个元素

回答by Sergei Dubinin

Keeping in mind Rocket's answer I prefer to use .index()approach like following:

记住 Rocket 的回答,我更喜欢使用.index()如下方法:

$.fn.isAfter = function(sel){
    return $(this).index() > $(sel).index();
};
$.fn.isBefore= function(sel){
    return $(this).index() < $(sel).index();
};

It seems more clear for reading/understanding and works perfectly in rows selection.

阅读/理解似乎更清晰,并且在行选择中完美运行。

回答by moomoo

The previous answers work fine IF the elements in question are siblings (which they are in the original question) but a more general solution would consider the following scenario:

如果所讨论的元素是兄弟元素(它们在原始问题中),则先前的答案工作正常,但更通用的解决方案将考虑以下情况:

<div id="top">    
    <div>
        <div>
           <h3 id="first">First</h3>
           <p>Hi</p>
           <p>Hello</p>
        </div>
    </div>
    <div>
        <h3 id="second">Second</h3>
        <p>Bye</p>
        <p>Goodbye</p>
    </div>
</div>

A more general solution would be:

更通用的解决方案是:

$.extend($.fn, {
    isBefore: function(sel, context) {
        // Get all element within the context.
        var all = $(context || document).find("*");
        return all.index(this[0]) < all.index($(sel));
    },

    isAfter: function(sel, context) {
        return !this.isBefore(sel, context);
    }
});

Where "context" is an optional parameter that merely limits the search area for jQuery to improve performance. I haven't performed any tests but "context" is probably unnecessary since $("*") seems to execute qualitatively fast. Also note that index() will return -1 is either element is not within the context.

其中“上下文”是一个可选参数,它仅限制 jQuery 的搜索区域以提高性能。我还没有执行任何测试,但“上下文”可能是不必要的,因为 $("*") 似乎在质量上执行得很快。另请注意,如果元素不在上下文中,则 index() 将返回 -1。

$("#first").isBefore("#second");  
// Gives the same result as
$("#first").isBefore("#second", "#top");

Of course this all assumes that by "before" and "after" you mean their order in the document model. If you are concerned about their relative positions on the display you would want to examine the elements display coordinates relative to the document as "relative", "fixed" and "absolute" CSS positions make anything possible.

当然,这一切都假设“之前”和“之后”是指它们在文档模型中的顺序。如果您担心它们在显示器上的相对位置,您可能想要检查元素相对于文档的显示坐标,因为“相对”、“固定”和“绝对”CSS 位置使一切成为可能。