簡體   English   中英

在jquery中監聽類的更改

[英]Listen for change of class in jquery

在jquery中是否有一種方法可以監聽節點類的更改,然后在類更改為特定類時對其執行某些操作? 具體來說,我正在使用jquery工具選項卡插件和幻燈片放映,並且正在播放幻燈片時,我需要能夠檢測焦點何時在特定選項卡/錨點上,以便我可以取消隱藏特定的div。

在我的具體例子中,我需要知道何時:

<li><a class="nav-video" id="nav-video-video7" href="#video7-video">Video Link 7</a></li>

添加了“current”類更改為以下內容:

<li><a class="nav-video" id="nav-video-video7 current" href="#video7-video">Video Link 7</a></li>

然后我想在那一刻取消隱藏div。

謝謝!

您可以綁定DOMSubtreeModified事件。 我在這里添加一個例子:

 $(document).ready(function() { $('#changeClass').click(function() { $('#mutable').addClass("red"); }); $('#mutable').bind('DOMSubtreeModified', function(e) { alert('class changed'); }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="mutable" style="width:50px;height:50px;">sjdfhksfh <div> <div> <button id="changeClass">Change Class</button> </div> 

http://jsfiddle.net/hnCxK/13/

以下是一些可能提供解決方案的其他發現:

  1. 最有效的檢測/監控DOM變化的方法?
  2. 如何檢測HTML元素的類何時更改?
  3. 監視JQuery中的DOM更改

正如在#2中所建議的那樣,為什么不將current添加的類(而不是ID)設置為當前並使用以下CSS處理顯示/隱藏操作。

<style type='text/css>
    .current{display:inline;}
    .notCurrent{display:none;}
</style>

在jquery中查看.on()也值得。

有了這樣的東西,你基本上有兩個選擇,回調或輪詢。

由於當DOM以這種方式變異(可靠地跨所有平台)時,您可能無法觸發事件,因此您可能不得不求助於輪詢。 為了更好一些,您可以嘗試使用requestAnimationFrame api,而不是僅僅使用setInterval這樣的東西。

采用最基本的方法(即使用setInterval並假設使用jQuery),您可以嘗試這樣的方法:

var current_poll_interval;
function startCurrentPolling() {
  current_poll_interval = setInterval(currentPoll, 100);
}
function currentPoll() {
  if ( $('#nav-video-7').hasClass('current') ) {
    // ... whatever you want in here ...
    stopCurrentPolling();
  }
}
function stopCurrentPolling() {
  clearInterval(current_poll_interval);
}

我知道這是舊的,但接受的答案使用DOMSubtreeModified ,現在已經為MutationObserver棄用了。 這是一個使用jQuery的例子( 在這里測試):

// Select the node that will be observed for mutations
let targetNode = $('#some-id');

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: false, subtree: false, attributeFilter: ['class'] };

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
    for (let mutation of mutationsList) {
        if (mutation.attributeName === "class") {
            var classList = mutation.target.className;
            // Do something here with class you're expecting
            if(/red/.exec(classList).length > 0) {
                console.log('Found match');
            }
        }
    }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode[0], config);

// Later, you can stop observing
observer.disconnect();

暫無
暫無

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

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