我有一個事件監聽器,當用戶在窗口中單擊。我想看看點擊的元素是否有任何具有特定ID的父元素。我使用jQuery的nearest()函數。但它總是返回真實。jQuery的最接近()似乎沒有找到父ID時,沒有
這是演示我的代碼的fiddle。
必須有一些重大的錯誤,因爲如果我改變從if($(event.target).closest('#activatemenu'))
標識加入任何其他ID
if($(event.target).closest('#rrrrrrr'))
它仍然返回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