繁体   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