[英]Selecting parent element of class using jQuery
JS:
$(function(){
$(".remove").click(function(){
$("<need the right selector>").hide();
});
});
HTML:
<div class="tag-collection">
<div class="key">PULMONARY_EMBOLISM <span class="remove">✘</span></div>
</div>
我想上面的jQuery代碼刪除整個div tag-collection
。 但是,我在頁面上會有很多tag-collection
div,並且我想確保當有人單擊“刪除”按鈕時,它僅刪除包含“刪除”按鈕的tag-collection
div。
如果您有很多,那么它將綁定較少的偵聽器,因此它更“有效” /更輕便:
$(function(){
$(document).on('click', 'span.remove', function() {
$(this).closest('.tag-collection').hide();
});
});
$(".remove").click(function(){
$(this) // points to clicked element
.closest('.tag-collection') // jump to parent tag-collection
.hide(); // hide that
});
$(function(){
$(".remove").click(function(){
$(this).parents('.tag-collection').hide();
});
});
強調第3行。
編輯:正如凱文B在下面指出的那樣,用closest()
替換parents()
可能更好,因為那樣只會選擇一個祖先。
您可以使用closest
方法,請嘗試以下操作:
$(function(){
$(".remove").click(function(){
$(this).closest('.tag-collection').remove();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.