jQuery:查找不是同级的下一个元素 [英] jQuery: Find next element that is not a sibling

查看:316
本文介绍了jQuery:查找不是同级的下一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下HTML:

Let's say I have following HTML:

<span>
    <span id="x1" class="x">X1</span>
</span>
<span>
    <span>
        <span id="x2" class="x">X2</span>
    </span>
</span>

$(this)<span id="x1" ...>.

找到与jQuery .x匹配的下一个元素的最佳方法是什么?
实际文档的结构不可预测,因此提供的HTML只是一个示例.

What is the best way to find next element matching .x with jQuery?
The structure of the actual document is unpredictable, so the HTML provided is only an example.

我不能使用nextAll,因为它只能找到同级.
如果执行$('.x'),它将找到所有内容,但是我必须进行迭代/比较.
有更好的解决方案吗?

I can't use nextAll as it only finds siblings.
If I do $('.x'), it finds all, but I'll have to iterate/compare.
Is there a better solution?

另请参见: http://jsfiddle.net/JZ9VW/1/.

推荐答案

选择所有类为x的元素,计算当前元素的索引并获取索引为+ 1的元素:

Select all elements with class x, calculate the index of the current element and get the element with the index + 1:

var $x = $('.x');
var $next = $x.eq($x.index(this) + 1);

之所以可行,是因为按文档顺序选择了元素.您只需在页面加载时一次选择所有.x元素(如果它们不是动态创建的).

This works because elements are selected in document order. You only have to select all .x elements once on page load (if they are not dynamically created).

这篇关于jQuery:查找不是同级的下一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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