简体   繁体   English

如何知道类何时更改/添加到HTML元素?

[英]How to know when a class changed/added to an HTML element?

I have a list that looks like this: 我有一个如下所示的列表:

<ul id="colors">
 <li class="variant on">red</li>
 <li class="variant off">blue</li>
 <li class="variant off">white</li>
 <li class="variant off">black</li>
</ul>

I want get an event when an item changes from off to on class changes, eg if the following happens: 我希望在项目从关闭更改为更改时获取事件,例如,如果发生以下情况:

 <li class="variant off">red</li>
 <li class="variant on">blue</li>

For that I tried to use livequery but I don't manage to get the events or set it right. 为此,我尝试使用livequery,但我没有设法获取事件或设置正确。

$('#colors li.on').livequery(function(){ 
                             console.log(this.text())
                          });

This would only be possible in modern browsers that supports the MutationObserver object. 这只能在支持MutationObserver对象的现代浏览器中实现。 You will not be able to observe DOM changes directly otherwise. 否则您将无法直接观察DOM更改。 You could always write some interceptors of the addClass function that would automatically raise events, but I would not recommend this. 您总是可以编写一些addClass函数的拦截器来自动引发事件,但我不建议这样做。 What you are trying to achieve is pretty bad design. 你想要实现的是非常糟糕的设计。 You should not rely on the DOM to keep track of your application state . 您不应该依赖DOM来跟踪您的应用程序状态

An ugly way to do it is to patch the jQuery functions with some intermediate functions of yours before running jQuery's implementation. 一个丑陋的方法是在运行jQuery的实现之前用你的一些中间函数修补jQuery函数。 You could run intermediate code on addClass and removeClass . 您可以在addClassremoveClass上运行中间代码。

For example, patching the addClass . 例如,修补addClass We take the original addClass 我们采用原始的addClass

jQuery.fn.addClass = (function(){
  var addClass = jQuery.fn.addClass;
  return function(){
    //do stuff here before running the original addClass
    //you could collect callbacks and run them here
    return addClass.apply(this,arguments);
  }
}());

The other way would be MutationObserver which currently is only supported by Chrome, Firefox and Safari. 另一种方式是MutationObserver ,目前只有Chrome,Firefox和Safari支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM