[英]Hooking document.createElement using function prototype
我想以這樣的方式掛鈎document.createElement函數,每次我創建一個div元素時,我的鈎子會將一個“foo”屬性附加到div。 這就是我目前所擁有的:
<script>
window.onload = function () {
console.log("document loaded");
document.prototype.createElement = function (input) {
var div = document.createElement(input);
console.log("createElement hook attached!");
if (input == "div")div.foo = "bar";
return div;
}
document.body.addEventListener('onready', function () {
var div = document.createElement("div");
console.log(div.foo);
});
}
</script>
當我在Chrome中運行時,我收到錯誤消息
Uncaught TypeError: Cannot set property 'createElement' of undefined test.html:4 window.onload
(我更改了上面錯誤消息中的行號以匹配我的代碼)
我錯在哪里? 我怎樣才能解決這個問題?
document
沒有.prototype
,因為它是一個實例對象而不是構造函數 document.createElement
,它最終會遞歸。 你需要在某處存儲對舊的引用,然后調用它。 嘗試這個
document.createElement = function(create) {
return function() {
var ret = create.apply(this, arguments);
if (ret.tagName.toLowerCase() === "div") {
ret.setAttribute("foo", "bar");
}
return ret;
};
}(document.createElement)
我建議不要覆蓋現有的功能,因為它們將來可能是只讀的。 我建議對DOM進行后期處理(div的快速遍歷比攔截每個元素的創建更快)和/或修改插入div的代碼以添加屬性。 或者,如果您真的想要修改創建的節點,那么更好的方法是Mutation Observers(HTML5):
http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers
這是比使用HTML4中已棄用的突變事件更好的選擇,並且覆蓋全局變量通常被認為是一種不好的做法,除非您正在創建填充或填充。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.