我正在检查与selected类最近的id是否为toshow。从代码中可以看出,条件应该是真的,但它在控制台中显示为false。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Demo part 1</title>
</head>
<body>
<div style="width:500px;">div (great-grandparent)
<ul>ul (second ancestor - second grandparent)
<div id="toshow"">ul (first ancestor - first grandparent)
<li>li (direct parent)
<button class="selected">span</span>
</li>
</ul>
</ul>
</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
console.log($(".selected").closest("[id]") == "toshow");
</script>
</html>
发布于 2020-12-31 07:31:36
closest是DOM选择器函数。结果是对元素的引用。您希望对照返回元素的id进行检查:
console.log($(".selected").closest("[id]").attr('id') == "toshow");
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Demo part 1</title>
</head>
<body>
<div style="width:500px;">div (great-grandparent)
<ul>ul (second ancestor - second grandparent)
<div id="toshow"">ul (first ancestor - first grandparent)
<li>li (direct parent)
<button class="selected">span</span>
</li>
</ul>
</ul>
</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
console.log($(".selected").closest("[id]").attr('id') == "toshow");
</script>
</html>
发布于 2020-12-31 07:34:55
您应该比较attr,它的返回元素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Demo part 1</title>
</head>
<body>
<div style="width:500px;">div (great-grandparent)
<ul>ul (second ancestor - second grandparent)
<div id="toshow"">ul (first ancestor - first grandparent)
<li>li (direct parent)
<button class="selected">span</span>
</li>
</ul>
</ul>
</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
console.log($(".selected").closest("[id]").attr("id") == "toshow");
</script>
</html>
https://stackoverflow.com/questions/65517875
复制相似问题