当前的问题是attrName
属性不是jQuery事件对象的一部分......您需要使用。下面是它的工作的例子:
var first_img = $("body").find("div").first();
first_img.on("DOMAttrModified", function (e) {
if (e.originalEvent.attrName === "class") {
console.log("##DOMAttrModified, class changed");
if ($(this).hasClass("current-image")) {
console.log("##Element has 'current-image' class, changing");
$(this).removeClass().addClass("previous-image");
}
}
});
setTimeout(function() {
first_img.addClass("current-image");
}, 1000);
DEMO:http://jsfiddle.net/R5rTy/1/
的setTimeout
是模拟事件发生随机。
显然,在所有的浏览器不支持DOMAttrModified
事件 - http://help.dottoro.com/ljfvvdnm.php#additionalEvents
UPDATE:
使用较新的MutationObserver
,下面说明了如何使用这两种思路:
var firstImg, observerConfig, firstImgObserver;
firstImg = $("body").find("div").first();
observerConfig = {
attributes: true,
childList: true,
characterData: true
};
firstImgObserver = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
var newVal = $(mutation.target).prop(mutation.attributeName);
if (mutation.attributeName === "class") {
console.log("MutationObserver class changed to", newVal);
} else if (mutation.attributeName === "id") {
console.log("MutationObserver id changed to", newVal);
}
});
});
firstImgObserver.observe(firstImg[0], observerConfig);
// later, you can stop observing
//observer.disconnect();
firstImg.on("DOMAttrModified", function (e) {
var newVal = $(this).prop(e.originalEvent.attrName);
console.log("DOMAttrModified", e.originalEvent.attrName, "changed to", newVal);
});
setTimeout(function() {
firstImg.addClass("previous-image").addClass("fdsa");
}, 1000);
DEMO:http://jsfiddle.net/ybGCF/
参考:
来源
2013-06-18 15:21:33
Ian
的'attrName'属性不是jQuery的事件的对象的一部分......你需要使用'e.originalEvent.attrName' – Ian
无关,但突变事件已被弃用。你可能想看看突变观察家 – PSL
@PSL我肯定会说这是相关的。提起贬低是非常重要的,非常重要。我看到了你对我的回答的评论 - 对不起,我们必须创建自己的小提琴并在同一时间发布。当我在这里看到你的评论时,我意识到这是一个好主意,至少用'MutationObserver'给出一个例子 – Ian