contains
のjQueryメソッドは、第2引数が第1引数の子または子孫であるとみなします。最初の引数はElementやDocumentのようなDOMオブジェクトでなければなりませんが、2番目の引数がDOMオブジェクトでなくても(jQueryコレクションを渡すなど)予期しない動作に気付きました。
この方法では、常に個々のノード(要素やドキュメントなど)を使用する必要があります。複数の項目をチェックする必要がある場合は、ループまたはイテレータメソッドを使用してください(以下のJSFiddleの例を参照してください)。
DOM(ドキュメントオブジェクトモデル)をツリーと考えてください。木には幹と枝があります。ルートはhtml
要素です。そこからあなたは枝head
とbody
を持っています。それらのそれぞれは、他の要素にさらに分岐します。各ブランチには、他の要素が含まれていてもいなくてもよい。特定のブランチ(個別にノードとして知られている)に他のノードが含まれている場合、それらをすぐに含むノードは、現在のノードの子ノードまたは子ノードと呼ばれます。それらの子ノード(それらの子、それらの子など)は、現在のノードの子孫として知られています。あなたが現在ここで、body
ノードを見ていた場合には、例えば、いくつかの収容するための識別、兄弟、および親/祖先ノードは、次のとおりです。ここ
html (parent of body and also an ancestor of body)
--> head (previous and prior sibling of body)
--> title
--> body (assume you are currently looking at this node)
--> header (this is a child and descendant of body)
--> div (this is a descendant of body)
--> section (this is a child and descendant of body)
--> div (this is a descendant of body)
--> p (this is a descendant of body)
--> p (this is a child and descendant of body)
--> span (this is a child and descendant of body)
--> footer (this is a child and descendant of body)
--> div (this is a descendant of body)
は、私があなたに作業例を表示するために作成した例です。
フィドルが消えた場合は、ここではHTMLとJavaScriptは次のとおりです。
<div id="first">
<span id="first-inner"></span>
</div>
<div id="second">
<span id="second-inner"></span>
</div>
<div id="loop">
<span id="loop-inner" class="check-loop"></span>
</div>
<span id="loop-outer" class="check-loop"></span>
<div id="extra-messages">
</div>
// Is #first-inner a descendant of #first?
if(jQuery.contains(jQuery("#first").get(0), jQuery("#first-inner").get(0))) {
jQuery("#first-inner").text("Span with id 'first-inner' is a descendant of the div with id 'first'");
} else {
jQuery("#first-inner").text("Span with id 'first-inner' is NOT a descendant of the div with id 'first'");
}
// Is #second-inner a descendant of #first?
if(jQuery.contains(jQuery("#first").get(0), jQuery("#second-inner").get(0))) {
jQuery("#second-inner").text("Span with id 'second-inner' is a descendant of the div with id 'first'");
} else {
jQuery("#second-inner").text("Span with id 'second-inner' is NOT a descendant of the div with id 'first'");
}
// Loop it!
jQuery(".check-loop").each(function(idx, item){
if(jQuery.contains(jQuery("#loop").get(0), item)) {
jQuery("#extra-messages").append(jQuery("<div>div</div>").text("Span with id '" + jQuery(item).attr("id") + "' is a descendant of the div with id 'loop'"));
} else {
jQuery("#extra-messages").append(jQuery("<div></div>").text("Span with id '" + jQuery(item).attr("id") + "' is NOT a descendant of the div with id 'loop'"));
}
});
出典
2016-09-07 17:28:23
Jim
jQueryのように定義されます、具体的にはちょうど
です* *これらの事のドキュメントを提供しません。 https://api.jquery.com/jQuery。/ – David
@Davidすでに読んでいますが、簡単な例で簡単に説明してください。 – Lucky
まあ、「DOM要素が別のDOM要素の子孫であるかどうかを確認する」* - > 'jQuery .contains(コンテナ、含む) '、私はそれがもっと簡単に説明することができるか分からないのですか? – adeneo