簡體   English   中英

使用 jQuery 刪除沒有特定類的 DOM 元素

[英]Remove DOM Element Without A Specific Class With jQuery

我試圖通過檢查是否缺少“md-panel-is-showing”類來使用 jQuery 刪除 DOM 中的 DIV。 但是,我無法將它從 DOM 中刪除,我不確定我是否錯誤地定位了該元素,或者我是否沒有檢查該類是否正確丟失。 幫助表示贊賞。

jQuery

setTimeout(function() {     
    var $dupe = $('.md-panel-outer-wrapper[style*="z-index: 150"]');
    console.log($dupe) //this works     
    if (!$($dupe).hasClass("md-panel-is-showing")) {
        $(this).remove(); //Doesn't remove
    }
}, 3000);

HTML

<div class="md-panel-outer-wrapper md-panel-is-showing"><!-- Content --></div>
<div class="md-panel-outer-wrapper"><!-- Content --></div>

嘗試以下代碼。 我們正在使用.not()方法形式的 jQuery。

setTimeout(function() {     
    $('.md-panel-outer-wrapper')
        .not('.md-panel-is-showing')
        .remove();
}, 3000);

not() 是 jQuery 中的一個內置函數,與 filter() 方法正好相反。 此函數將返回與具有特定“id”或“class”的選定元素不匹配的所有元素。 選擇器是不被選擇的被選擇元素。

嘗試這個

setTimeout(function() {     
    $('.md-panel-outer-wrapper')
        .not('.md-panel-is-showing')
        .remove();
}, 3000);

代碼中的this指的是全局對象。 因此,在這種情況下使用特定的目標選擇器。 如果有一個事件處理程序this被設置為在其上收聽者被放置的DOM元素:

 setTimeout(function() { var $dupe = $('.md-panel-outer-wrapper[style*="z-index: 150"]'); if (!$($dupe).hasClass("md-panel-is-showing")) { $('.md-panel-is-showing').remove(); //Doesn't remove } }, 3000);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="md-panel-outer-wrapper md-panel-is-showing"> Md Panel Content </div> <div class="md-panel-outer-wrapper"> Outer Wrapper Content </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM