找到DOM中稍后出现的下一个元素

时间:2015-05-06 23:21:15

标签: javascript jquery performance

在javascript中可能更好,但这肯定包括jQuery或任何这样的库。

我想在下面的示例中找到第一个os.path.splitext(path)

对于提出.nextnextAll的类似问题,有很多答案......两者在这里都没用:

siblings
$(function(){
  $('.result').text(
    $('.origin').nextAll('.next').text()
      || $('.origin').siblings('.next').text()
      || 'both failed'
  )
})

此外,最兼容(浏览器和库明智)和大多数性能(速度和代码行数较少)的方式是这样做的吗?

2 个答案:

答案 0 :(得分:4)

基于awesome answer @mrtsherman,我编写了这个更完整的解决方案并对其进行了测试,以便在Chrome和Safari上运行:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="whatever">
  <p class="result"></p>
  <p class="origin">1</p>
</div>
<p class="next">2</p>
<p class="next">3</p>
$(function() {
  $('.result').text(
    $('.origin').below('.next').text()
  );
});

(function($) {
  $.fn.below = function(sel) {
    var $result = $(sel).first();
    if ($result.length <= 0) {
      return $result;
    }
    $result = [];
    var thisIndex = $('*').index($(this));
    var selIndex = Number.MAX_VALUE; // Number.MAX_SAFE_INTEGER is not yet fully supported
    $(sel).each(function(i, val) {
      var valIndex = $('*').index($(val));
      if (thisIndex < valIndex && valIndex < selIndex) {
        selIndex = valIndex;
        $result = $(val);
      }
    });
    return $result;
  };
})(jQuery);

我可能会try to submit a PR for this on jQuery lib,因为我相信 ......

这应该是jQuery的核心方法! :P

事实上,I just ran a very simplistic test on this,对于这个简单的例子,它的表现甚至优于<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="whatever"> <p class="result"></p> <p class="origin">1</p> </div> <p class="next">2</p> <p class="next">3</p>。几乎快两倍! :○

答案 1 :(得分:2)

如果您可以使用IE9 +,可以尝试compareDocumentPosition()。一个简单的jQuery插件看起来像这样:

$.fn.below = function(selector) {
  var el = this[0],
      compare = $(selector),
      nextEl;

  compare.each(function(i, item) {
    var result = el.compareDocumentPosition(item);
    // get the first one that appears below `this`
    if (result === 4) {
      nextEl = $(item);
      return false;
    }
  });
  return nextEl || $();
};

这可能会被清理/简化一点。但它很好用。这是一个码头:

http://codepen.io/ZevanRosser/pen/QbjZmr?editors=101

compareDocumentPosition()返回一个具有以下含义的数字:

p1.compareDocumentPosition(p2)

1:没有关系,这两个节点不属于同一个文档。

2:第一个节点(p1)位于第二个节点(p2)之后。

4:第一个节点(p1)位于第二个节点(p2)之前。

8:第一个节点(p1)位于第二个节点(p2)内。

16:第二个节点(p2)位于第一个节点(p1)内。

32:没有关系,或者两个节点是同一元素上的两个属性。

请注意,上述内容仅限于: http://www.w3schools.com/jsref/met_node_comparedocumentposition.asp