我有一个名为x()的函数。我想在每次更改任意节点的innerHTML属性时调用x()(请注意,我希望为所有节点调用x(),而不仅仅是1个节点)。最初,我认为innerHTML是HTMLElement对象的一个函数,并且想要修补它,但是在Chrome的Javascript控制台中玩游戏后,我在HTMLElement对象中找不到innerHTML函数。
我还考虑过使用DOMAttrModified事件(http://help.dottoro.com/ljdchxcl.php),但Chrome不支持。欢迎任何建议。
答案 0 :(得分:1)
@Cecchi的答案很酷,但它并不是真正适用于所有HTMLElement实例的真正的猴子补丁。自那个答案以来,浏览器具有新功能。
这很棘手,因为HTMLElement.prototype.innerHTML
是一个制定者,但我能够让它像这样工作:
//create a separate JS context that's clean
var iframe = document.createElement('iframe');
//have to append it to get access to HTMLElement
document.body.appendChild(iframe);
//grab the setter. note that __lookupSetter__ is deprecated maybe try getOwnPropertyDescriptor? anyways this works currently
let origSetter = iframe.contentWindow.HTMLElement.prototype.__lookupSetter__('innerHTML');
//mangle the global HTMLElement in this JS context
Object.defineProperty(HTMLElement.prototype, 'innerHTML', {
set: function (val) {
console.log('innerHTML called', val);
// *** do whatever you want here ***
return origSetter.call(this, val); //allow the method to be called like normal
}
});
现在测试一下:
document.createElement('div').innerHTML = '<p>oh, hey</p>';
//logs: innerHTML called <p>oh, hey</p>
答案 1 :(得分:0)
根据您正在开发的内容以及您需要的浏览器支持(听起来只是Chrome,希望只是现代Chrome),您可以查看MutationObserver
界面(例如借用并稍微修改一下{ {3}}:
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type);
x(mutation.target);
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// select the target nodes
Array.prototype.slice.apply(
document.querySelectorAll('.nodes-to-observe')
).forEach(function(target) {
observer.observe(target, config);
});
// later, you can stop observing
observer.disconnect();
MutationObserver
的更多内容可以在这里找到:
这是在Chrome 18&amp; Firefox 14。