jQuery中的类名更改事件 [英] Class name change Event in jQuery
问题描述
当元素类更改时,有没有办法在jQuery中触发事件?
Is there a way to trigger a event in jQuery when an elements classes are changed?
示例:
<img class="selected" />
into
<img class="selected newclass" />
触发事件
和
<img class="selected" />
into
<img class="" />
触发事件
推荐答案
你可能可以用一点麻烦的方式解决问题。 Hook
.addClass()& .removeClass(),如下所示:
You might be able to workaround on a little hacky way. Hook
.addClass() & .removeClass() like so:
var _addClass = $.fn.addClass,
_removeClass = $.fn.removeClass;
$.fn.addClass = function(){
// do whatever here
return _addClass.apply(this, arguments);
}
$.fn.removeClass = function(){
// do whatever here
return _removeClass.apply(this, arguments);
}
这样,假设你只是想观看元素类更改与 jQuery ,您可以触发添加
或删除
类中的任何代码。再次,只要你使用jQuery,这个例子。
That way, assuming you are just interested in watching elements class changes with jQuery, you can trigger whatever code on adding
or removing
classes. Again, just if you are using jQuery, for this example.
当然,你可以 hook
和覆盖
任何JavaScript函数的方式。
Of course, you can hook
and overwrite
any javascript function that way.
As Nick Craver
在评论中,还有其他一些jQuery方法可以添加
或 remove
一个元素类。所有这些都需要 hook
,即:
As Nick Craver
mentioned in a comment, there are several other jQuery methods which can add
or remove
an elements class. You would have to hook
all of those, namely:
.addClass()
.removeClass()
.toggleClass()
.removeAttr('class')
.attr('class', 'changed')
除非您确切知道调用哪些方法来操作类,否则您将不得不关心所有这些。
unless you know exactly which methods are called to manipulate a class, you would have to care about all of those.
这篇关于jQuery中的类名更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!