简体   繁体   English

为什么不对DOM元素函数应用工作?

[英]Why doesn't apply work on DOM element functions?

Sample code 样例代码

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

The error 错误
Firefox: Firefox:

TypeError: 'setAttribute' called on an object that does not implement interface Element. TypeError:'setAttribute'在未实现接口Element的对象上调用。

Chrome: 铬:

Uncaught TypeError: Illegal invocation 未捕获的TypeError:非法调用

apply is working just fine. apply工作正常。 It is calling the setAttribute function and inside that function the value of this is what you set it to). 它调用setAttribute函数和函数内部的价值this是你将它设置为)。

We can't see what it is you are setting it to because you are passing this without showing us what its value is. 我们看不到您将其设置为什么,因为您在传递this未向我们显示其价值。

Clearly, this is not a DOM element, so you can't set a DOM attribute on it. 显然, this不是DOM元素,因此无法在其上设置DOM属性。

If you had called document.body.getAttribute() then inside setAttribute the value of this would be document.body , which is a DOM element. 如果您曾呼吁document.body.getAttribute()然后里面setAttribute的值, this将是document.body ,这是一个DOM元素。

You can see it working if this is a DOM element in this example: 在此示例中,如果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> 

This works : 这有效:

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

In your code (if you execute outside any function), this refers to the window element, so your code is equivalent to : 在您的代码中(如果您在任何函数外部执行), this是指window元素,因此您的代码等效于:

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

which is not allowed 这是不允许的

Is there a specific reason why you need apply ? 有什么特定的原因需要apply吗? As this is your window object. 因为this是您的窗口对象。 Applying an id to it is probably not very useful or even allowed. id应用于它可能不是很有用,甚至不允许。 From what I know, I would go with this method: 据我所知,我会使用这种方法:

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

Feel free to correct me :) 随时纠正我:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM