Javascript 如何检测 HTML 元素的类何时更改?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6034161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:58:08  来源:igfitidea点击:

How can I detect when an HTML element’s class changes?

javascriptjqueryhtmlcssclass

提问by James

<div class="current"></div>
<a href="#">text</a>

How do I detect when e.g. a .liveclass is added to this <div>and do something when it happened?

我如何检测何时.live添加了一个类<div>并在它发生时做一些事情?

For example, if class is changed, then hide the link.

例如,如果更改了类,则隐藏链接。

I have a minified script that makes changes on the <div>'s class. It's too big for me to find the place where it happens, so I'm searching for some way to catch the class change.

我有一个缩小的脚本,可以对<div>'s 类进行更改。它太大了,我找不到它发生的地方,所以我正在寻找某种方法来捕捉班级变化。

采纳答案by jwueller

There are DOM events, but they are far from perfect and not available in most browsers. In other words: Not possible(reliably). There are hacks like intervals and checking it in each iteration, but if you need to do something like this, your design is probably screwed. Keep in mind that such things will be slow and that there will always be a delay. The smaller the delay, the slower the application. Do not do that.

有 DOM 事件,但它们远非完美,在大多数浏览器中都不可用。换句话说:不可能(可靠)。有像间隔这样的技巧,并在每次迭代中检查它,但如果你需要做这样的事情,你的设计可能会搞砸。请记住,这样的事情会很慢,而且总会有延迟。延迟越小,应用程序越慢。不要那样做。

回答by Darin Dimitrov

You may checkout the following articlefor some ideas.

您可以查看以下文章以获取一些想法。

回答by jeroen.verhoest

I don't know if the class you add to the link is always the same but if so, why don't you use CSS for this.

我不知道您添加到链接的类是否总是相同的,但如果是这样,为什么不为此使用 CSS

<style type='text/css>
  .myaddedclass{display:none}
</style>

回答by Paul D. Waite

If you just need to figure this out once (i.e. not in code), Google Chrome's web inspector shows DOM changes live. Not sure if that'd help your situation out though.

如果您只需要解决一次(即不在代码中),Google Chrome 的网络检查器会实时显示 DOM 更改。不确定这是否会帮助您解决问题。