直接的问题是attrName
属性不是 jQuery 事件对象的一部分……你需要使用e.originalEvent.attrName
. 这是它的工作示例:
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);
演示:http: //jsfiddle.net/R5rTy/1/
setTimeout
就是模拟随机发生的事件。
显然,DOMAttrModified
并非所有浏览器都支持该事件 - http://help.dottoro.com/ljfvvdnm.php#additionalEvents
更新:
使用 newer 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);
演示:http: //jsfiddle.net/ybGCF/
参考: