如何使用jQuery查找具有ID属性的下一个元素
How to find the next element which has an ID attribute using jQuery
当我单击链接时,我需要找到下一个具有 ID 属性的<section>
并返回其 ID。
因此,鉴于以下标记和 javascript,我希望单击链接将"section_3"写入控制台。
<section id="section_1">
<a href="#" class="findNext">Find</a>
</section>
<section></section>
<section id="section_3"></section>
<section id="section_4"></section>
和
$('a.findNext').click(function() {
var nextSectionWithId = $(this).closest("section").next("section[id]");
if (nextSectionWithId) {
var sectionId = nextSectionWithId.attr('id');
console.log(sectionId)
}
});
但这行不通。我已经在jsFiddle中设置了代码。
任何想法为什么这不起作用?
尝试:
var nextSectionWithId = $(this).closest("section").nextAll("section[id]:first");
或
var nextSectionWithId = $(this).closest("section").nextAll("section[id]").filter(':first');
小提琴
您不能使用 next,因为 next 将仅在 next 元素中查找匹配项。因此,您可以在选择器中将 nextAll 与 :first 结合使用。
更新
您也可以使用 jquery 中的 first() 方法来获取集合中的第一个元素,这似乎是一个更快的选择。
var nextSectionWithId = $(this).closest("section").nextAll("section[id]").first();
可能是这个原因:
因为 :first 是一个 jQuery 扩展,而不是 CSS 规范的一部分,所以使用 :first 的查询不能利用本机 DOM querySelectorAll() 方法提供的性能提升。要在使用 :first 选择元素时获得最佳性能,请先使用纯 CSS 选择器选择元素,然后使用 .filter(":first")。
库特西 @T.J. 克劳德
使用 .nextAll()
演示
var nextSectionWithId = $(this).closest("section").nextAll("section[id]")[0].id;
演示
var nextSectionWithId = $(this).closest("section").nextAll("section[id]").eq(0).attr('id');
演示
var nextSectionWithId = $(this).closest("section").nextAll("section[id]").attr('id');
相关文章:
- 滚动到容器中的下一个元素-几乎到了
- 后焦点更改为IE 11中的地址栏,而不是转移到表单中的下一个控件
- 使用CSS或js,使用动态选择器选择任意li的下一个元素
- 使用ajax将数据从一个步骤发送到下一个步骤的3步表单
- AngularJS&JSON-从Previous&下一个对象
- 使用向下箭头键(与tab键一样)聚焦下一个输入
- 来自文档或下一个静态父级的事件委派
- angularjs移除焦点上的活动类并添加到下一个项目
- 禁用旋转木马中的下一个按钮和上一个按钮
- 当按下一个键时,请多次按下不同的键
- 正在加载下一个帖子
- jQuery - 根据属性在所选选项之后的下拉列表中获取下一个选项的总值
- jQuery-根据属性在下拉列表中获取所选选项之后的下一个选项的值
- 按属性值获取数组中的下一个对象
- 如何使用jQuery查找具有ID属性的下一个元素
- Lexer错误:意外的下一个字符(属性名称中的波浪号~)
- 根据指定的数据属性创建一个包含值和文本的select下拉选项
- ES的正确称呼是什么?下一个静态类属性
- 从属性并使用JavaScript传递到下一个html页面
- 如何获得链接的href属性,并将其设置为下一个兄弟使用jquery的href