0

我有一组嵌套DIV的,我需要从内盒中找到每个外盒。根据jQuery API,该closest()方法获取与选择器匹配的第一个祖先元素。所以我试过这个:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css"><!--
div{
    margin: 1em;
    padding: em;
    border: 1px solid black;
}
--></style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"><!--
jQuery(function($){
    $(".direccion-html").closest("div").css({borderColor: "red"});
});
//--></script>
</head>
<body>

<div>
    <div class="direccion-html">Foo</div>
</div>
 <div>
    <div class="direccion-html">Bar</div>
</div>

</body>
</html>

但是,我的最接近()选择器正在获取元素本身,而不是它的任何祖先。我究竟做错了什么?这一定是一个明显的错误,但我无法理解......

更新:

我从尼克的回答中写了这个:

jQuery(function($){
    $(".direccion-html").each(function(){
        $(this).parents("div:first").css({borderColor: "red"});
    });
});
4

1 回答 1

2

.closest()从当前元素开始,如果匹配则最接近。如果您想要最近的不是元素,请使用.parents()相同的选择器 and :first,如下所示:

jQuery(function($){
    $(".direccion-html").parents("div:first").css({borderColor: "red"});
});

你可以在这里测试一下。或者,适用于许多元素的替代路线:

jQuery(function($){
    $(".direccion-html").parent().closest("div").css({borderColor: "red"});
});

在此处测试该版本

于 2010-10-18T09:36:41.550 回答