2017-02-13 108 views
0

我曾嘗試使用setAttribute()方法的jQuery如下所述:爲什麼我們不能在jQuery中使用setAtrribute函數?

$(p).setAttribute('class','first'); 

然而,沒有工作,所以我代替setAttributeattr()方法。

$(p).attr('class','first'); 

它在我使用上述代碼時起作用。

我只想知道爲什麼當我使用setAttribute()時它不起作用,爲什麼當我使用attr()時它工作?

+0

'p.setAttribute('class','first');' –

回答

4

.setAttribute()是一個函數在JavaScript的工作DOM元素在哪裏.attr()是一個jQuery函數工作的jQuery對象(DOM對象)

,你可以通過做

$(p)[0].setAttribute('class','first'); 

OR

p.setAttribute('class','first'); // no need to wrap in $ 
檢查
+1

我明白了,謝謝澄清我的問題:) @Dhaval Marthak – Harish

+0

@Harish Gla它幫助:) –

相關問題