javascript 将事件绑定到类名的更改
javascript / jQuery 是否可以将函数绑定到 DOM 元素的类名更改或分配新类?
Is it possible in javascript / jQuery to bind a function to a DOM element's classname changing or being assigned a new class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,更新类时不会触发广泛支持的事件。你必须进行民意调查。有些浏览器支持 DOM 突变事件,但从来不支持已完全支持跨浏览器,请参阅链接页面上的警告。
显然,如果您的代码更改了类,您可以创建一个用于执行此操作的函数,并始终使用该函数而不是直接更改它,但如果您正在寻找代码之外对其进行更改,我不这样做没有看到轮询的替代方案。
如果您进行轮询,请务必在所有目标浏览器上进行测试,并在轮询代码中实际执行尽可能少的工作。很容易做得过度(减慢页面速度)。
No, there's no broadly-supported event fired when the class is updated. You'll have to poll. Some browsers support DOM mutation events, but it's never been completely supported cross-browser, see the warning on the linked page.
Obviously, if it's your code that changes the class, you could create a function you use to do that and always use that function rather than changing it directly, but if you're looking for changes to it outside of your code, I don't see an alternative to polling.
If you poll, be sure to test on all of your target browsers and do as little work actually in the polling code as you can. It's easy to over-do it (slowing down the page).