【问题标题】:getAttribute in prototype but throws undefined原型中的 getAttribute 但抛出未定义
【发布时间】:2014-12-26 07:09:31
【问题描述】:

我在浏览器中遇到了一个非常奇怪的问题:我有一个 HTMLElement elt 是一个图像,但 elt.getAttribute 是未定义的,尽管 elt.__proto__ 包含一个 getAttribute 方法。

我检查了很多东西:

elt.nodeType             => 1
elt.__proto__            => HTMLImageElement {click: function, getAttribute: function, setAttribute: function, removeAttribute: function, getAttributeNode: function…}
elt.__proto__.getAttribute => function getAttribute() { [native code] }
elt.getAttribute         => undefined
elt.setAttribute         => function setAttribute() { [native code] }
elt.getAttributeNS       => function getAttributeNS() { [native code] }
elt.getAttributeNode     => function getAttributeNode() { [native code] }
elt.getAttributeNodeNS   => function getAttributeNodeNS() { [native code] }
typeof elt               => object

知道这可能来自哪里吗?我不知道这是从哪里来的。

【问题讨论】:

  • 提供您的验证码
  • 代码太多了。我应该将我的问题转变为:“当对象是 dom 元素时,为什么有人可以做object.setAttribute = undefined

标签: javascript jquery dom


【解决方案1】:

我尝试了最简单的方案:

<img name="elt" src="...">


<script>

    var elt = document.images.namedItem("elt");

    alert(elt.getAttribute);     // function getAttribute() { [native code] }   
    alert(elt.getAttribute == elt.__proto__.getAttribute);     // true

</script>

我得到了预期,这意味着原型链有效。 我的建议是检查以下输出:

elt.getAttribute == elt.__proto__.getAttribute

如果它们在您的情况下看起来不相等,那么您做了一些破坏原型链的事情。 我可以模拟你的场景如下:

<img name="elt" src="...">


<script>

    var elt = document.images.namedItem("elt");

    alert(elt.getAttribute);     // function getAttribute() { [native code] }   
    alert(elt.getAttribute == elt.__proto__.getAttribute);     // true

    elt.getAttribute = undefined;

    alert(elt.getAttribute == elt.__proto__.getAttribute);     // false

</script>

因此我认为 elt.getAttribute 已在您的代码中的某处定义并设置为“未定义”。

【讨论】:

    猜你喜欢
    • 2015-01-29
    • 2018-01-28
    • 2019-10-19
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    相关资源
    最近更新 更多