jquery のドキュメントにclosest
は次のように書かれています。
.closest( selector [, context ] )
...
context
タイプ: Element
一致する要素が見つかる可能性がある DOM 要素。コンテキストが渡されない場合は、代わりに jQuery セットのコンテキストが使用されます。
私が理解しているように、太字のテキストは、2 つのステートメントが同等であることを意味します。
set.closest("a");
set.closest("a", set.context);
set
jquery セットは どこにありますか。
ただし、そうではないようです。
var context = $("#inner")[0];
var set = $("#el", context);
// the set's context is correctly the "inner" element
set.text("context: " + set.context.id);
// if the set's context is used, this closest should match nothing, but it matches and sets the color
set.closest("#outer").css("color", "red");
// with the context explicitly set, the "outer" is not found and no background color is set
set.closest("#outer", set.context).css("background-color", "blue");
#outer{
width: 100px;
height: 100px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="outer">
<div id="inner">
<div id="el"></div>
</div>
</div>
ご覧のとおり、コンテキストが明示的に設定されていない場合、#outer
要素が によって検出されるため、セットのコンテキストは使用されていないようですclosest
。明示的に設定すると、#outer
が正しく検出されません。
ドキュメントが間違っているだけですか、それとも何か不足していますか?