2015-10-15 71 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'); 

隨意指正:)

相關問題