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>

ただし、私のclosest()セレクターは、要素自体をフェッチしており、その祖先はフェッチしていません。私は何が間違っているのですか?それは明らかなエラーであるに違いありませんが、私はそれを得ることができません...

アップデート:

私はニックの答えからこれを構成しました:

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

1 に答える 1

2

.closest()現在の要素から開始します。一致する場合は、最も近い要素です。要素ではない最も近いものが必要な場合.parents()は、同じセレクターで使用し、次の: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 に答える