通过jQuery更改类时,我怎么知道? [英] How can I get to know while a class changed via jQuery?

查看:46
本文介绍了通过jQuery更改类时,我怎么知道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是div:

<div id="components-reconnect-modal" class="components-connecting-show">
  <div id="1">
  <div id="2">
  <div id="3">
  <div id="4">
</div>

id不会永远更改,但类将由第三方js库更改.

The id will not change forever but the class will change by a third-party js library.

根据不同的类显示不同的子div,我需要了解#components-reconnect-modal的类是否发生变化.

I need to get to know while the class of #components-reconnect-modal changes, according to the different classes show the different child div.

我该如何实现?

谢谢.

推荐答案

您必须听取元素中所做的更改.您可以尝试使用 MutationObserver

You have to listen to the changes made in the element. You can try with MutationObserver

MutationObserver 界面提供了监视功能对DOM树进行的更改.它旨在替代DOM3事件规范中较早的突变事件"功能.

The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature which was part of the DOM3 Events specification.

演示:

// Listen to the changes in the header element and add row
var target = document.querySelector('#components-reconnect-modal');

setTimeout(function() {
  target.className = "myClass"; // change class after 2 seconds
}, 2000)

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log('New class is: ' +target.getAttribute('class'));
  });
});

var config = {
  attributes: true,
  childList: true,
  characterData: true
};

observer.observe(target, config);

// otherwise
observer.disconnect();
observer.observe(target, config);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="components-reconnect-modal" class="components-connecting-show">
  <div id="1">
  <div id="2">
  <div id="3">
  <div id="4">
</div>

这篇关于通过jQuery更改类时,我怎么知道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆