【问题标题】:Listen for change of class in jquery在 jquery 中监听类的变化
【发布时间】:2010-09-17 00:09:23
【问题描述】:

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。

谢谢!

【问题讨论】:

标签: javascript jquery


【解决方案1】:

您可以绑定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/

【讨论】:

【解决方案2】:

我知道这是旧的,但接受的答案使用 DOMSubtreeModified,现在已弃用 MutationObserver。这是一个使用 jQuery 的示例(测试一下here):

// 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();

【讨论】:

    【解决方案3】:

    以下是一些可能提供解决方案的其他发现:

    1. Most efficient method of detecting/monitoring DOM changes?
    2. How can I detect when an HTML element’s class changes?
    3. Monitoring DOM Changes in JQuery

    正如 #2 中所建议的,为什么不将 current 设为一个添加的类,而不是一个 ID,并让以下 CSS 处理显示/隐藏操作。

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

    也许值得研究一下.on() in jquery

    【讨论】:

    • 谷歌把我带到了这里。我查看了“.on()”,但不清楚将类添加到元素时可能触发哪个事件。我和OP的情况类似,需要在添加类时触发,但我无法绑定到原始点击事件,因为插件在点击事件上调用了preventDefault。
    • 我发布这个问题已经有一段时间了,坦率地说,我忘记了我是如何处理它的。使用 CSS 隐藏/取消隐藏 div 将是显而易见的解决方案,但我很确定我一定有一些额外的事情正在发生,这让我无法保持那么简单。无论如何,我选择了@jsuar 解决方案,因为它包含一些有用的链接。
    【解决方案4】:

    有了这样的东西,你基本上有两个选择,回调或轮询。

    由于您可能无法在 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      相关资源
      最近更新 更多