【发布时间】:2012-07-31 03:10:46
【问题描述】:
我想以这样一种方式挂钩到 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!哇,祝你好运…… -
在浏览器中处理 DOM 对象是一件非常痛苦的事情。 Prototype JS 库没有成功的原因之一。您可能希望围绕您希望扩展的任何对象创建一个包装器对象。 perfectionkills.com/whats-wrong-with-extending-the-dom
-
不要手动构建 dom,尤其是在没有库的情况下。除非这是一个个人学习项目,否则请使用模板引擎和库来进行 DOM 操作,或者您正在乞求维护和可移植性的噩梦。拦截 createElement 绝不应该是必要的,而且将来可能并不总是这样。
标签: javascript