如何在jQuery中找到已知类的父类名称
给定一个HTML文档,任务是在给定的类名的帮助下获得一个元素的父类。
步骤 1:
- on()方法是用来选择选定元素的事件处理程序。这意味着当用户点击按钮时,就会调用该函数。
- closest()方法用于返回所选元素的第一个祖先。
- 检查祖先(父)类是否存在,然后返回类名,否则返回不存在。
例子:这个例子使用closest()方法来获得元素的第一个匹配的祖先。
<!DOCTYPE html>
<html>
<head>
<title>
How to find a parent class
name with a known class
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP" style=
"font-size: 17px; font-weight: bold;">
</p>
<div class="parent">
<div class="child"></div>
</div>
<button>
click here
</button>
<p id="GFG_DOWN" style=
"color: green; font-size: 24px; font-weight: bold;">
</p>
<script>
('#GFG_UP').text('Click on the button to see result');
('button').on('click', function() {
var object = ('.child').closest('.parent');
if (object.length) {
('#GFG_DOWN').text("className = '.child'"
+ " with parentName = '.parent'" + " Exists");
}
else {
$('#GFG_DOWN').text("Not Exists");
}
});
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
步骤 2:
- on()方法是用来选择选定元素的事件处理程序。这意味着当用户点击按钮时,就会调用该函数。
- parent()方法是用来返回所选元素的所有祖先的。
- 检查祖先(父)类是否存在,然后返回类名,否则返回不存在。
例子:这个例子使用parents()方法来获得元素的所有匹配的祖先。
<!DOCTYPE html>
<html>
<head>
<title>
How to find a parent class
name with a known class
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP" style=
"font-size: 17px; font-weight: bold;">
</p>
<div class="parent">
<div class="child"></div>
</div>
<button>
click here
</button>
<p id="GFG_DOWN" style=
"color: green; font-size: 24px; font-weight: bold;">
</p>
<script>
('#GFG_UP').text('Click on the button to see result');
('button').on('click', function() {
var object = ('.child').parents('.parent');
if (object.length) {
('#GFG_DOWN').text("className = '.child'"
+ " with parentName = '.parent'" + " Exists");
}
else {
$('#GFG_DOWN').text("Not Exists");
}
});
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。