简体   繁体   English

在jquery中监听类的更改

[英]Listen for change of class in jquery

Is there a way in jquery to listen for a change to a node's class and then take some action on it if the class changes to a specific class? 在jquery中是否有一种方法可以监听节点类的更改,然后在类更改为特定类时对其执行某些操作? Specifically, I'm using the jquery tools tabs plugin with the slideshow and as the slideshow is playing, I need to be able to detect when the focus is on a particular tab/anchor so that I can unhide a specific div. 具体来说,我正在使用jquery工具选项卡插件和幻灯片放映,并且正在播放幻灯片时,我需要能够检测焦点何时在特定选项卡/锚点上,以便我可以取消隐藏特定的div。

In my specific example, I need to know when: 在我的具体例子中,我需要知道何时:

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

changes to the following with the class "current" added: 添加了“current”类更改为以下内容:

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

Then I want to unhide a div at that moment. 然后我想在那一刻取消隐藏div。

Thanks! 谢谢!

You can bind the DOMSubtreeModified event. 您可以绑定DOMSubtreeModified事件。 I add an example here: 我在这里添加一个例子:

 $(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/ http://jsfiddle.net/hnCxK/13/

Here are some other finds that might provide a solution: 以下是一些可能提供解决方案的其他发现:

  1. Most efficient method of detecting/monitoring DOM changes? 最有效的检测/监控DOM变化的方法?
  2. How can I detect when an HTML element's class changes? 如何检测HTML元素的类何时更改?
  3. Monitoring DOM Changes in JQuery 监视JQuery中的DOM更改

And as it was suggested in #2, why not make current a class that is added, rather than a ID, and have the following CSS handle the show/hide action. 正如在#2中所建议的那样,为什么不将current添加的类(而不是ID)设置为当前并使用以下CSS处理显示/隐藏操作。

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

Might also be worth it to look into .on() in jquery . 在jquery中查看.on()也值得。

With anything like this you have essentially two options, callbacks or polling. 有了这样的东西,你基本上有两个选择,回调或轮询。

Since you possibly can't get an event to be triggered when the DOM mutates in this way (reliably across all platforms) you may have to resort to polling. 由于当DOM以这种方式变异(可靠地跨所有平台)时,您可能无法触发事件,因此您可能不得不求助于轮询。 To be a bit nicer about it, you could try using the requestAnimationFrame api rather than just using something like setInterval natively. 为了更好一些,您可以尝试使用requestAnimationFrame api,而不是仅仅使用setInterval这样的东西。

Taking the most basic approach (ie using setInterval and assuming jQuery) you might try something like this: 采用最基本的方法(即使用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);
}

I know this is old, but the accepted answer uses DOMSubtreeModified , which has now been deprecated for the MutationObserver . 我知道这是旧的,但接受的答案使用DOMSubtreeModified ,现在已经为MutationObserver弃用了。 Here's an example using jQuery (test it out here ): 这是一个使用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