jQuery中的类名更改事件 [英] Class name change Event in jQuery

查看:95
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆