Jquery教程
Jquery动效
Jquery HTML/CSS
Jquery 事件
jquery常用

Jquery parent()方法

jQuery中的 parent()方法查找给定选择器的直接父级。它是jQuery中的内置函数。此方法仅遍历DOM树中的单个级别,并返回所选元素的直接父级。
parent()方法与 parents( )方法,因为它们都向上移动到DOM树并返回父元素。但不同之处在于 parents()方法在DOM树中向上遍历多个级别,并返回给定选择器的所有祖先,包括祖父母,曾祖父母等,而 parent()方法仅遍历单个级别,并且仅返回给定选择器的直接父级。

语法

$(selector).parent(filter)
以上语法中的 选择器 表示要搜索其父项的选定元素。上面语法中的 filter 是用于指定选择器表达式的可选参数,用于缩小搜索范围。

Example1

在此示例中,我们没有使用 parent()方法的可选参数。这里,有一个div元素,其中包含 ul 元素,标题为 h2 和一个段落元素。
我们正在应用 parent()方法来搜索标题h2的父级。如果我们使用 parents()方法而不是 parent()方法,则标题h2的所有祖先(包括body元素)都将突出显示。
<!DOCTYPE html>
<html>
<head>
<style>
.main *{
  font-size: 20px;
  border: 2px solid black;
  color: black;
  padding: 10px;
  margin: 17px;
}
</style>
<script src = "/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function fun(){
$(document).ready(function(){
  $("h2").parent().css({ "font-size": "30px", "color": "blue", "border": "6px dashed blue"});
});
}
</script>
</head>
<body class = "main">
  <div> div
    <ul> ul
      <h2> Heading h2
          <p> Paragraph element </p>
      </h2>
    </ul>
</div>
<button onclick = "fun()"> click me </button>
  </body>
</html>
输出:
执行上述代码后,输出将为-
jQuery parent()方法
单击给定按钮后,输出为-
jQuery parent()方法

Example2

在此示例中,我们使用 parent()的可选参数方法来查找第一个 paragraph元素的父级。在这里,有多个段落元素,但是我们必须找到第一个段落元素的父元素。因此,我们将伪选择器( : first )作为 parent()方法的可选值。
<!DOCTYPE html>
<html>
<head>
<style>
.main *{
  font-size: 20px;
  border: 2px solid black;
  color: black;
  padding: 5px;
  margin: 10px;
}
</style>
<script src = "/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function fun() {
$(document).ready(function(){
  $("p").parent(":first").css({"color": "blue", "border": "3px dashed blue"});
});
}
</script>
</head>
<body class = "main"> body
    <div> div1
  <div> div2
    <h2> h2
          <p> Paragraph element </p>
    </h2>
<h2> h2
          <p> Paragraph element </p>
    </h2>
</div>
  </div>
<button onclick = "fun()"> click me </button>
</body>
</html>
执行上述代码后,输出将为-
jQuery parent()方法
单击给定按钮后,输出为-
jQuery parent()方法

Example3

在此示例中,我们使用 parent()的可选参数方法,用于查找给定选择器的特定父级。在这里,有三个具有不同父项的段落元素。我们正在找到段落元素的 h2 父级。因此,要实现相同目的,我们必须将 h2 作为 parent()方法的可选值。
<!DOCTYPE html>
<html>
<head>
<style>
.main *{
  font-size: 20px;
  border: 2px solid black;
  color: black;
  padding: 5px;
  margin: 10px;
}
</style>
<script src = "/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function fun() {
$(document).ready(function(){
  $("p").parent("h2").css({"color": "blue", "border": "5px dashed blue"});
});
}
</script>
</head>
<body class = "main"> body
    <div> div1
    <div> div2
          <p> Paragraph element </p>
    </div>
<h2> h2
          <p> Paragraph element </p>
    </h2>
<ul> ul
          <p> Paragraph element </p>
    </ul>
  </div>
<button onclick = "fun()"> click me </button>
</body>
</html>
输出:
执行上述代码后,输出将为-
jQuery parent()方法
单击给定按钮后,输出为-
jQuery parent()方法
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4