jQuery 中的类名更改事件
当元素类更改时,有没有办法在 jQuery 中触发事件?
示例:
<img class="selected" />
into
<img class="selected newclass" />
触发事件
And
<img class="selected" />
into
<img class="" />
触发事件
Is there a way to trigger a event in jQuery when an elements classes are changed?
Examples:
<img class="selected" />
into
<img class="selected newclass" />
triggers an event
And
<img class="selected" />
into
<img class="" />
trigger an event
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您也许可以通过一些技巧来解决。
钩子
.addClass() & .removeClass() 像这样:这样,假设您只是有兴趣观察元素类的更改jQuery,您可以在
添加
或删除
类时触发任何代码。同样,如果您在本例中使用 jQuery。当然,您可以通过这种方式
挂钩
和覆盖
任何 JavaScript 函数。正如 Nick Craver 在评论中提到的,还有其他几种 jQuery 方法可以添加或删除元素类。您必须
hook
所有这些,即:除非您确切知道调用哪些方法来操作类,否则您必须关心所有这些。
You might be able to workaround on a little hacky way.
Hook
.addClass() & .removeClass() like so:That way, assuming you are just interested in watching elements class changes with jQuery, you can trigger whatever code on
adding
orremoving
classes. Again, just if you are using jQuery, for this example.Of course, you can
hook
andoverwrite
any javascript function that way.As
Nick Craver
mentioned in a comment, there are several other jQuery methods which canadd
orremove
an elements class. You would have tohook
all of those, namely:unless you know exactly which methods are called to manipulate a class, you would have to care about all of those.
我认为这是不可能的。
事件基于用户操作,因此单击、双击、鼠标悬停等都是用户操作。
您可能希望在每个元素上设计某种数据块,然后构建一个集成到 jQuery
.class()
和.attr()
方法中的小型系统,以便当您的代码更新一个类,它将向包含前一个类的元素添加数据,然后如果前一个类与正在设置的类不同,则触发您的事件。
我所说的集成的意思是
你可以这样做
希望这能给你一些帮助
I do not think this is possible.
Events are based on user actions so click,dblclick,mouseover etc are all user actions.
You may want to devise some kind of data block on each element and then build a small system that integrates into jQuery
.class()
and.attr()
methods so that when your code updates a class it will add data to that element holding the previous class,then if the previous class is different to class being set then trigger your events.
What i mean by integrate is
then you can do like
Hope this gives you some help