我很困惑为什么在这个简单的例子中,.closest 的第二次遍历似乎失败了:
function testClosest(element) {
let firstParentDiv = element.closest('div');
console.log('First Parent Div ID:', firstParentDiv.id);
let secondParentDiv = firstParentDiv.closest('div');
console.log('Second Parent Div ID:', secondParentDiv ? secondParentDiv.id : 'None');
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test for .closest() Method</title>
</head>
<body>
<div id="grandparent">
Grandparent
<div id="parent">
Parent
<div id="child">
Child
<button onclick="testClosest(this)">Test Closest</button>
</div>
</div>
</div>
</body>
</html>
我期望第二个控制台日志显示“parent”,但它再次记录“child”。 为什么第二次遍历尝试不起作用?
最接近的祖先元素或本身,与选择器匹配。如果没有这样的元素,则为 null。