jQuery中元素在DOM中的相对位置 [英] Relative position in DOM of elements in jQuery

查看:112
本文介绍了jQuery中元素在DOM中的相对位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定两个jquery对象,我是否可以通过某种方式判断哪个在文档树中比另一个更领先"?换句话说,带有文档

Given two jquery objects, Is there some way I tell which one is "further ahead" in the document tree than the other? In other words, with a document

 <p id="p1" ></p>
 <div id="div1">
    <p id="p2"></p>
 </div>
 <p id="p3"></p>

是否有某些功能如此起作用?

Is there some function that behaves thus?

$("#p1").isBefore($("#p2")); // == true
$("#p3").isBefore($("#p2")); // == false
$("#p1").isBefore(#("#p3")); // == true

请注意,我关心的是文档在HTML树中的位置,而不是屏幕上的实际位置.

Note that I care about position in the HTML tree of the document, not physical position on the screen.

推荐答案

您可以创建一个执行此操作的函数,如下所示:

You can make a function that does this, like this:

(function($) {
  $.fn.isBefore = function(elem) {
    if(typeof(elem) == "string") elem = $(elem);
    return this.add(elem).index(elem) > 0;
  }
})(jQuery)

您可以在此处尝试,第一行是这样,因此也可以直接选择器字符串,例如:

You can try it out here, the first line is so it can also take a selector string directly, for example:

$("#p1").isBefore("#p2");

这是 .add() 附加元素(或选择器)(jQuery保留在其中)文档顺序),然​​后检查它是否是两者中的第二个.

What this does is .add() the additional element (or selector) (which jQuery keeps in document order) and then checks if it's the second of the two.

如果运行该选择器的元素有多个,则如果其中的任何元素在传入"元素或选择器之前",则返回true,因此给定标记,例如true,因为至少有一个<p>出现在"#p2之前".

If the selector this is run against has more than one element, this returns true if any of those elements are "before" the passed in element or selector, so given your markup for example $("p").isBefore("#p2") would be true, since at least one <p> occurs "before" #p2.

这篇关于jQuery中元素在DOM中的相对位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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