how do I override appendChild()?

半世苍凉 提交于 2020-01-01 04:45:06

问题


appendChild = function(message) {
    console.log("intercepted!");
}

using the code above does not seem to work.

Anyone knows?


回答1:


What you might want to replace is Element.prototype.appendChild but it's probably a bad idea.

This example adds the text intercepted in the inserted element :

var f = Element.prototype.appendChild;
Element.prototype.appendChild = function(){f.apply(this, arguments);arguments[0].innerHTML="!Intercepted!"; };
document.body.appendChild(document.createElement("div"));

Demonstration




回答2:


It is ill advised to overwrite native functions, but if you do it than make sure you return the appended element as well to prevent problems with code that uses the returned value of the native "appendChild" function:

window.callbackFunc = function(elem, args) {
  // write some logic here
}
window.f = Element.prototype.appendChild;
Element.prototype.appendChild = function() {
    window.callbackFunc.call(this, arguments);
    return window.f.apply(this, arguments);
};


来源:https://stackoverflow.com/questions/14265219/how-do-i-override-appendchild

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!