2015-10-15 73 views
1

示例代码为什么不适用于DOM元素函数?

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

错误
火狐:

TypeError: 'setAttribute' called on an object that does not implement interface Element.

铬:

Uncaught TypeError: Illegal invocation

+1

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

回答

2

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>

+0

解释它。在我的代码中,我使用了Array.map函数中的apply,所以'this'引用了新函数。 – qw3n

2

这工作:

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

在你的代码(如果执行外任何函数),this引用窗口元素,所以你的代码等同于:

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

这是不允许的

0

是否有一个具体的原因,你需要apply?由于this是您的窗口对象。对其应用id可能不是很有用,甚至是不允许的。据我所知,我会去用这种方法:

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

随意指正:)

相关问题