jQuery:查找不是同级的下一个元素

编程入门 行业动态 更新时间:2024-10-22 20:34:20
本文介绍了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?

另请参见: jsfiddle/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:查找不是同级的下一个元素

本文发布于:2023-11-30 04:13:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648678.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!