jQuery 遍历 - next() 方法实例

231 篇文章 6 订阅
188 篇文章 2 订阅

jQuery 遍历 - next方法实例

实例

查找每个段落的下一个同胞元素,仅选中类名为 “selected” 的段落:

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="/jquery/jquery.js"></script>
</head>

<body>
  <p>qipa250</p>
  <p class="selected">Hello 奇葩天地网</p>
  <div><span>And www.QiPa250.com</span></div>

<script>
  $("p").next(".selected").css("background", "yellow");
</script>

</body>
</html>

运行结果:

在这里插入图片描述

查看源码

<html><head>
  <script type="text/javascript" src="/jquery/jquery.js"></script>
</head>

<body>
  <p>qipa250</p>
  <p class="selected" style="background: yellow none repeat scroll 0% 0%;">Hello 奇葩天地网</p>
  <div><span>And www.QiPa250.com</span></div>

<script>
  $("p").next(".selected").css("background", "yellow");
</script>



</body></html>

定义和用法

next() 获得匹配元素集合中每个元素紧邻的同胞元素。如果提供选择器,则取回匹配该选择器的下一个同胞元素。

详细说明

如果给定一个表示 DOM 元素集合的 jQuery 对象,.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’);

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="/jquery/jquery.js"></script>
</head>

<body>
<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>

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

</body>
</html>

在这里插入图片描述

这次调用的结果是,项目 4 被设置为红色背景。由于我们没有应用选择器表达式,紧跟的这个元素很明确地被包括为对象的一部分。如果我们已经应用了选择器,在包含它之前会检测是否匹配。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值