使用jQuery获取div中的下一个元素 [英] Getting the next element in a div with jquery

查看:827
本文介绍了使用jQuery获取div中的下一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我们有这个html代码

Say that we have this html code

<div id="test">
     <h2>Title</h2>
     <p>lorem ipsum</p>
</div>

还有这个jQuery

And this jQuery

$("#test h2").text("Changed Title");

现在什么是继续向下滚动到<p>并更改其文本而又不向上移动一级的正确方法. 像next()只会寻找下一个h2一样,但是有什么东西使兄弟姐妹与元素类型无关.可能是next("p");之类的东西?

Now what is the correct way to continue down to the <p> and also change it's text, without going up one level. Like next() will only look for the next h2, but is there something that gets the sibling independent of element type. Something like next("p"); maybe?

推荐答案

next选择下一个元素:默认情况下,它不仅选择相同类型的元素.

next chooses the next element: by default it does not only select an element of the same type.

$('#test h2').next();      // selects the p
$('#test h2').next('p');   // selects the p
$('#test h2').next('h2');  // does not select the p

除非提供选择器,否则next 选择下一个兄弟元素.因此,您可以执行以下操作:

Unless you provide a selector, next will choose the next sibling element. You can therefore do this:

$('#test h2').text('Changed title').next().text('Changed text');

这篇关于使用jQuery获取div中的下一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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