简体   繁体   中英

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.

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

This would only be possible in modern browsers that supports the MutationObserver object. You will not be able to observe DOM changes directly otherwise. You could always write some interceptors of the addClass function that would automatically raise events, but I would not recommend this. What you are trying to achieve is pretty bad design. You should not rely on the DOM to keep track of your application state .

An ugly way to do it is to patch the jQuery functions with some intermediate functions of yours before running jQuery's implementation. You could run intermediate code on addClass and removeClass .

For example, patching the addClass . We take the original 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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