繁体   English   中英

使用jQuery获取div中的下一个元素

[英]Getting the next element in a div with jquery

说我们有这个html代码

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

还有这个jQuery

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

现在,什么是继续向下进入<p>并更改其文本而不向上一级的正确方法。 就像next()只会寻找下一个h2一样,但是有什么东西使兄弟姐妹与元素类型无关。 类似于next("p"); 也许?

您正在寻找的命令是siblings("p")

这是您的示例,已更新:

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

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

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

除非您提供选择器,否则next 选择下一个兄弟元素。 因此,您可以这样做:

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

.next( 'p' )将解决问题:

$("#test h2").text("Changed Title")
             .next( 'p' )
             .text( 'Another change' );

jQuery文档中

获取匹配的元素集中每个元素的紧随其后的同级。 如果提供了选择器,则仅当与该选择器匹配时才检索下一个同级。

在这里查看示例小提琴

确实,您可以使用.next('p')方法来实现:

$("#test h2").next('p').text("...");

.next('p')确实可以工作。 只需将其链结在最后即可。 像这样:

$('#test h2').text("Changed Title").next('p').text('I changed too');

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

就像你建议的那样

$("#test").next("p").text('yada');

甚至更好:

$("#test h2").text("Changed Title").next("p").text('yada');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM