.next()

.next( [ selector ] ) 官网原E文: jQuery

描述: 取得一个包含匹配的元素集合中每一个元素紧邻的后面同辈元素的元素集合。如果提供一个选择器,它检索下一个匹配选择器的兄弟元素。

  • version added: 1.0.next( [ selector ] )

    selector选择器字符串,用于确定到哪个前辈元素时停止匹配。

如果提供的jQuery代表了一组DOM元素, .next()方法允许我们找遍元素紧邻的后面同辈元素所在的DOM树,构建新的匹配元素的jQuery对象。

该方法选择性地接受同一类型选择表达,我们可以传递给$()函数。如果紧随兄弟匹配选择器,它在新建成的jQuery对象中留下;否则,它被排除在外。

考虑一个页面上一个简单的列表:

<ul>
   <li>list item 1</li>
   <li>list item 2</li>
   <li class="third-item">list item 3</li>
   <li>list item 4</li>
   <li>list item 5</li>
</ul>

如果我们从第三个项目开始,我们可以找到它之后的元素:

$('li.third-item').next().css('background-color', 'red');

调用后的结果是项目4变成红色背景,由于我们没有提供一个选择器表达式,祖先元素都是返回的jQuery对象的一部分。如果我们有提供一个选择的表达式,只有在这些匹配的项目将包括在内。

Examples:

Example: Find the very next sibling of each disabled button and change its text "this button is disabled".

<!DOCTYPE html>
<html>
<head>
  <style>

  span { color:blue; font-weight:bold; }
  button { width:100px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <div><button disabled="disabled">First</button> - <span></span></div>
  <div><button>Second</button> - <span></span></div>

  <div><button disabled="disabled">Third</button> - <span></span></div>
<script>$("button[disabled]").next().text("this button is disabled");</script>

</body>
</html>

Demo:

Example: Find the very next sibling of each paragraph. Keep only the ones with a class "selected".

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <p>Hello</p>

  <p class="selected">Hello Again</p>
  <div><span>And Again</span></div>
<script>$("p").next(".selected").css("background", "yellow");</script>

</body>
</html>

Demo:

jQuery 1.6 API 中文版Clove整理、修订