2012-07-04 105 views
0

说,我们有这样的HTML代码获取下一个元素与jQuery的一个div

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

这jQuery的

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

那么什么是继续向下的<p>,也是正确的方法改变它的文本,而不会升到一个级别。 像next()只会寻找下一个h2,但是有没有获得独立元素类型的兄弟姐妹。像next("p");可能是什么?

+0

http://api.jquery.com/帮助... – Christoph

回答

2

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'); 
0

没错,你可以通过使用.next('p')方法做到这一点:

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

.next('p')确实工作。最后链接它。像这样:

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

2

你要找的命令是siblings("p")

这里就是你们的榜样,更新:

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

就像你所说,

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

甚至更​​好:

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

.next('p')将这样的伎俩:

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

jQuery docu

获取匹配元素集合中每个元素的紧随其后的同胞。如果提供了一个选择器,只有当它与该选择器匹配时才会检索下一个兄弟。

请参阅example fiddle here