使用函数原型挂钩document.createElement [英] Hooking document.createElement using function prototype

查看:299
本文介绍了使用函数原型挂钩document.createElement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以这样一种方式挂钩document.createElement函数,每次我创建一个div元素时,我的钩子都会将一个foo属性附加到div。这就是我目前的情况:

I want to hook onto the document.createElement function in such a way that, every time I create a div element, my hook will attach a "foo" attribute to the div. This is what I have currently:

<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中运行时,我收到错误消息

When I run this in Chrome, I get an error saying

Uncaught TypeError: Cannot set property 'createElement' of undefined test.html:4 window.onload

(我更改了上面错误信息中的行号以匹配我的代码)

(I changed the line number in the error message above to match my code)

我在这里错了什么?我该如何解决这个问题?

What am I wrong here? How can I fix this?

推荐答案


  • document 没有 .prototype ,因为它是一个实例对象而不是构造函数

  • 你正在调用新 document.createElement 在你的新函数中,它最终会递归。你需要在某个地方存储对旧的引用,然后调用它。

  • 你正在设置属性而不是属性

  • 这是非常脆弱的东西做和不保证工作。它似乎适用于chrome和firefox,但在旧的IE中不起作用

    • document doesn't have a .prototype, since it's an instance object and not a constructor function
    • you are calling the new document.createElement in your new function, it would end up in recursion. You need to store reference to the old one somewhere, and call that.
    • You are setting a property instead of attribute
    • This is extremely fragile thing to do and not guaranteed to work. It appears to work in chrome and firefox, but won't work in old IE
    • 试试这个

      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)
      

      http://jsfiddle.net/NgxaK/2/

      这篇关于使用函数原型挂钩document.createElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆