jQuery在特定元素之后获取DOM中的下一个匹配项

scu*_*ffe 5 javascript jquery dom hierarchy jquery-selectors

我讨厌承认它,但我一直试图弄清楚如何做到这一点.

例如假装你有以下结构:

<div>
  ...
  <div>
    <ul>
      <li>
        <a href="..."><img class="foo"/></a><!-- "previous" -->
      </li>
      <li>
        <a href="..."><img class="bar"/></a>
      </li>
      <li>
        <a href="..."><img class="foo"/></a><!-- I'm at this node -->
      </li>
      <li>
        <a href="..."><img class="baz"/></a>
      </li>
      <li>
        <a href="..."><img class="foo"/></a><!-- "next" 1 -->
      </li>
    </ul>
  </div>
  ...
  <div>
    <ul>
      <li>
        <a href="..."><img class="foo"/></a><!-- "next" 2 -->
      </li>
      <li>
        <a href="..."><img class="baz"/></a>
      </li>
      <li>
        <a href="..."><img class="foo"/></a><!-- "next" 3 -->
      </li>
      <li>
        <a href="..."><img class="bar"/></a>
      </li>
    </ul>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我在与上面突出显示的 "foo"节点相关的jQuery事件处理程序中.我想找到一个"下一个" img元素"foo".

但是有两个问题.

  1. 我只想选择DOM中比我当前节点更远的"foo"元素(例如"之前的"foo,并且不需要当前的foo)
  2. 虽然我已示出的嵌套作为以下精确的图案,生成的代码是/可以被嵌套在任何级别...因而,我不能只是做.parent().父().父().兄弟姐妹( ).find()......等

如果你可以想象,每次浏览器向DOM添加一个节点时,它都会递增一个计数器,并为索引分配...你可以检索...我想要的是:

var here = $(this).getIndexInDOM();//e.g. returns 347
$('img.foo').each(function(){
  if($(this).getIndexInDOM() > here){//is this past our current index?
    doSomething($(this));//use it
    break;
  }
});
Run Code Online (Sandbox Code Playgroud)

这个.getIndexInDOM()方法显然在jQuery中不存在......但我很好奇是否有人有解决方案来获取我所追求的"下一个"元素.

我现在能想到的唯一解决方案是非常优雅,并且在DOM的后半部分中会表现得非常糟糕......

//using vanilla JavaScript
var thisImg = theCurrentImageIHave;//some reference to the DOM element
var found = false;
for(var i=0;i<document.images.length;i++){
  if(found){
    if(document.images[i].className == 'foo'){
      doSomething(document.images[i]);
      break;
    }
  } else {
    if(document.images[i] == thisImg){
      found = true;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

use*_*716 14

在点击处理程序中,试试这个:

示例: http ://jsfiddle.net/QVphP/ (单击蓝色框以向下一个添加边框)

var $foo = $('img.foo');  // get all .foo images

var idx = $foo.index( this );  // get the index position of "this"
                               //    relative to all the .foo images found

var next = $foo.eq( idx + 1 ); // grab the .foo for the incremented index
Run Code Online (Sandbox Code Playgroud)