ユーザーがウィンドウをクリックしたときのイベントリスナーがあります。クリックされた要素に特定のIDを持つ親要素があるかどうかを確認したい。私はそのためにjQuery closest()関数を使用します。しかし、それは常に真実を返します。jQuery closest()は、存在しない場合に親IDを見つけるように見えます。
ここに私のコードを示すfiddleがあります。
私は他のどのID
if($(event.target).closest('#rrrrrrr'))
へif($(event.target).closest('#activatemenu'))
からIDを変更した場合、それはまだtrueを返しますので、いくつかの主要なエラーが存在しなければなりません。フィドルで
コード:
$(function() {
\t $(document).click(function(event) {
if($(event.target).closest('#activatemenu')) {
\t \t \t \t
$('.wrap').prepend('<p>the clicked element has a parent with the id of activatemenu</p>');
}else{
\t $('.wrap p').remove();
}
});
});
.stuff{
width:300px;
height:150px;
border:red 2px solid;
}
.otherstuff{
width:400px;
height:400px;
background:purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div id="activatemenu">
<div>
<div>
<div class="stuff">
<p>Here is some text</p>
</div>
</div>
</div>
</div>
<div class="otherstuff">
<p>Other stuff!</p>
</div>
</div>
あるいは、使用はい、私は私が投稿する前に、 "activemenu" タイプミスを修正し、それを保存するのを忘れ - 私は今ことを更新しました。よく説明されています。 – Galivan