当通过Javascript/JQuery更改HTML文件的类名时,我需要调用JS函数。
<html xmlns = "http://www.w3.org/1999/xhtml" class = "A">
-
-
-
-
-
</html>
现在,类名A根据某些条件在运行时被更改,每当这个类名发生更改时,我需要调用另一个JS函数。
我正在从document.documentElement.className/document.documentElement.classList获得类名,并试图添加EventListener来实现这个目标,但没有成功。
你能告诉我。
谢谢和问候,阿尼基特
发布于 2016-10-20 17:49:40
var prevClass=element.className; setInterval(function(){ //check classname==prevClasss }, 1000);
这将每1秒检查一次类名是否与前一个类名不同,如果更改了类名,则需要实现必要的步骤。
发布于 2016-10-20 17:43:50
首先,您应该在检查条件的同一位置启动您的函数。但是,正如我假设的那样,由于某种原因不能这样做,您需要检查DOM的更改。
要做到这一点,您可以使用MutationObserver -您可以在这里找到带有示例的文档:https://developer.mozilla.org/pl/docs/Web/API/MutationObserver i有相当好的浏览器支持:http://caniuse.com/#feat=mutationobserver
示例
// select the target node
var target = document.documentElement;
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log('Fire something here on: ', mutation.type);
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);这是基于示例完成的,因此可能不是完美的,而是经过测试的,并且似乎如您所期望的那样工作。
https://stackoverflow.com/questions/40161007
复制相似问题