【问题标题】:How to observe adding class to div如何观察向 div 添加类
【发布时间】:2018-05-30 17:21:25
【问题描述】:

在我的div中我想观察他的类,所以当这个类passed被添加到我的div中时,我执行了一些js函数。

初始 div:<div id="1" class="allow"></div>

添加新类后:<div id="1" class="allow passed"></div>

我要执行的函数:

function fill() {
        jQuery('#check').show();
        jQuery('#check-val').hide();
    }

【问题讨论】:

  • 为什么不从添加传递类的方法中调用fill()?
  • 好问题,但我无权访问@Taplar
  • 你可能想看看这个答案stackoverflow.com/questions/1950038/…
  • @Austin Truex 未更改课程但已添加,我在发布之前看到了该问题:)
  • 使用 Austin 的建议,然后使用 .hasClass() 检查是否是您想要的课程

标签: javascript jquery events


【解决方案1】:

您还可以在该 div 上使用突变观察器来检测何时添加了一个类。注意突变观察者的用法。https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

    var observer = new MutationObserver(function(mutations) {
       mutations.forEach(function(mutation) {
         if (mutation.attributeName === "class") {
            if ($(mutation.target).hasClass('passed')){
                    alert("passed class was added");
                    fill();
           }
         }
     });
  });

observer.observe(document.getElementById('1'), {
  attributes: true
});

这是一个 jsfiddle https://jsfiddle.net/e37am2hq/

【讨论】:

  • 可以准确检查这个添加的类passed
  • 我修改了我的答案和 jsfiddle。是这个意思吗?
  • 使用 jQuery hasClass 函数。如果最后没有通过,上面的函数可能会失败。
  • 刚刚批准了您的编辑@DnyaneshwarSupe。 hasClass() 更干净。是的,.passed 必须是列表中的最后一个类。
  • @Austin Truex,对不起,但没有,在您的 setTimeout(function() { $("#1").addClass('passed'); }, 3000) 中,如果我将 ``addClass('passed');` 替换为 addClass('no-passed');,它仍然会检测到它
猜你喜欢
  • 2020-04-07
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 2018-01-10
  • 1970-01-01
  • 2012-01-21
  • 1970-01-01
相关资源
最近更新 更多