我想以这种方式挂钩到document.createElement函数上,每次创建div元素时,我的挂钩都会将“foo”属性附加到div。这是我目前:使用函数原型挂接document.createElement
<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'!哇,祝你好运.. – 2012-07-30 18:56:29
与DOM对象混合是一个非常痛苦的事情跨浏览器做。 Prototype JS库没有成功的原因之一。您可能希望围绕您希望扩展的任何位置创建一个包装对象。 http://perfectionkills.com/whats-wrong-with-extending-the-dom/ – 2012-07-30 19:15:08
不要手动构建dom,尤其是没有库。除非这是个人学习项目,否则使用模板引擎和库来执行DOM操作,或者您正在寻求维护和便携性的噩梦。截取createElement是不必要的,并且这在将来可能不会总是可能的。 – 2012-07-30 19:22:25