【问题标题】:Why doesn't apply work on DOM element functions?为什么不适用于 DOM 元素函数?
【发布时间】:2015-10-15 14:19:34
【问题描述】:

示例代码

document.body.getAttribute.apply(this,['id']);
document.body.setAttribute.apply(this,['id','test']);

错误
火狐:

TypeError:在未实现接口 Element 的对象上调用了“setAttribute”。

铬:

未捕获的类型错误:非法调用

【问题讨论】:

  • 你从console.log(this)得到什么,因为Firefox的错误信息清楚地表明this不是一个元素。

标签: javascript dom


【解决方案1】:

apply 工作正常。它正在调用setAttribute 函数,而在该函数内部,this 的值就是您设置的值。

我们无法看到您将其设置为什么,因为您传递了 this 而没有向我们展示它的值是什么。

很明显,this 不是 DOM 元素,所以你不能在它上面设置 DOM 属性。

如果您调用了document.body.getAttribute(),那么在setAttribute 内部,this 的值将是document.body,这是一个 DOM 元素。

如果this 在本例中是一个 DOM 元素,您可以看到它的工作原理:

document.querySelector('div').setID = function () {
    document.body.setAttribute.apply(this,['id','test']);
}

document.querySelector('div').setID();
document.querySelector('div').innerHTML = document.querySelector('div').id;
<div></div>

【讨论】:

  • 这就解释了。在我的代码中,我在 Array.map 函数中使用了 apply ,因此 this 引用了新函数。
【解决方案2】:

这行得通:

document.body.setAttribute.apply(document.body,['id','test']);
document.body.getAttribute.apply(document.body,['id']);

在您的代码中(如果您在任何函数之外执行),this 指的是窗口元素,因此您的代码相当于:

window.setAttribute("id","test");

这是不允许的

【讨论】:

    【解决方案3】:

    您需要apply 是否有特定原因?因为this 是您的窗口对象。对它应用id 可能不是很有用,甚至是不允许的。据我所知,我会采用这种方法:

    document.body.getAttribute('id');
    document.body.setAttribute('id','test');
    document.body.getAttribute('id');
    

    欢迎指正:)

    【讨论】:

    • 谢谢,这很简单也很完整。正在努力获取这个简单的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    相关资源
    最近更新 更多