小码哥的IT人生

首页 > JS > jQuery

jQuery 遍历 - prev() 方法 概述

jQuery 2022-06-01 17:59:50小码哥的IT人生shichen

jQuery 遍历 - prev() 方法

实例

检索每个段落,找到类名为 "selected" 的前一个同胞元素:

$("p").prev(".selected")

完整实例:

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
  <div><span>Hello</span></div>
  <p class="selected">Hello Again</p>
  <p>And Again</p>
<script>
  $("p").prev(".selected").css("background", "yellow");
</script>
</body>
</html>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

定义和用法

prev() 获得匹配元素集合中每个元素紧邻的前一个同胞元素,通过选择器进行筛选是可选的。

.prev(selector)
参数 描述
selector 字符串值,包含用于匹配元素的选择器表达式。

详细说明

如果给定一个表示 DOM 元素集合的 jQuery 对象,.prev() 方法允许我们在 DOM 树中搜索这些元素的前一个同胞元素,并用匹配元素构造一个新的 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').prev().css('background-color', 'red');

完整实例:

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.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').prev().css('background-color', 'red');
</script>
</body>
</html>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

此处调用的结果是将项目 2 设置为红色背景。由于我们未应用选择器表达式,前一个元素很自然地成为了对象的一部分。如果已应用选择器,则会在包含元素之前,检测元素是否匹配选择器。

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024