开发者

JavaScript/jQuery: Monitor change to element?

Is there any way (aside from creating a new event) that I can t开发者_运维知识库ell when a particular CSS class has been added to an element?


If you don't have access to the code that's adding the class, there's a jQuery plugin called livequery that will allow you to run code when elements are added to the DOM (or when you do things like add a class to an element).

http://brandonaaron.net/code/livequery/docs

$('div.myClass').livequery(function() {
     alert('myClass was added');
});

$('#someDiv').addClass("myClass");  // The livequery code will run

This works specifically with jQuery methods.


You could extend jQuery's addClass() to fire an event when it adds a class. However, this means you'll have to add classes always with this method.

If you don't do that, you'll have to poll and look for differences in the class attribute. I don't recommend doing that. Besides performance, you'll need to handle classes being removed too.


There is a DOM Level 3 specification to detect changes to an elements attributes, it is supported in a couple of browsers... Also IE supports an onpropertychange (http://msdn.microsoft.com/en-us/library/ms536956(VS.85).aspx) event too.

It's probably not going to be enough though. Your best bet is use window.setInterval() and check if the value has changed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜