在jquery中监听类的更改

Sna*_*awa 26 javascript jquery

在jquery中是否有一种方法可以监听节点类的更改,然后在类更改为特定类时对其执行某些操作?具体来说,我正在使用jquery工具选项卡插件和幻灯片放映,并且正在播放幻灯片时,我需要能够检测焦点何时在特定选项卡/锚点上,以便我可以取消隐藏特定的div.

在我的具体例子中,我需要知道何时:

<li><a class="nav-video" id="nav-video-video7" href="#video7-video">Video Link 7</a></li>
Run Code Online (Sandbox Code Playgroud)

添加了"current"类更改为以下内容:

<li><a class="nav-video" id="nav-video-video7 current" href="#video7-video">Video Link 7</a></li>
Run Code Online (Sandbox Code Playgroud)

然后我想在那一刻取消隐藏div.

谢谢!

小智 26

您可以绑定DOMSubtreeModified事件.我在这里添加一个例子:

HTML

$(document).ready(function() {
  $('#changeClass').click(function() {
    $('#mutable').addClass("red");
  });

  $('#mutable').bind('DOMSubtreeModified', function(e) {
    alert('class changed');
  });
});
Run Code Online (Sandbox Code Playgroud)

JavaScript的

<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>
Run Code Online (Sandbox Code Playgroud)

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

  • [DOMSubtreeModified](https://developer.mozilla.org/en-US/docs/Web/Events/DOMSubtreeModified)已弃用,请使用[MutationObserver](https://developer.mozilla.org/en-US/docs/ Web/API/MutationObserver)代替. (6认同)

cod*_*key 7

我知道这已经过时了,但接受的答案使用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();
Run Code Online (Sandbox Code Playgroud)


JSu*_*uar 3

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

\n\n
    \n
  1. 检测/监控 DOM 变化的最有效方法?
  2. \n
  3. 如何检测 HTML element\xe2\x80\x99s 类何时发生更改?
  4. \n
  5. 在 JQuery 中监控 DOM 变化
  6. \n
\n\n

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

\n\n
<style type=\'text/css>\n    .current{display:inline;}\n    .notCurrent{display:none;}\n</style>\n
Run Code Online (Sandbox Code Playgroud)\n\n

可能还值得研究一下jquery 中的 .on()

\n

  • 谷歌把我带到了这里。我查看了“.on()”,但不清楚当将类添加到元素时可能会触发哪个事件。我的情况与OP类似,需要在添加类时触发,但我无法绑定到原始点击事件,因为插件在点击事件上调用preventDefault。 (2认同)