2011-08-29 82 views
8

主要的現代瀏覽器支持動態設置/檢索自定義屬性,除IE系列之外。我如何在所有瀏覽器中設置/獲取我的自定義屬性?設置/獲取動態自定義屬性

這是我到目前爲止已經試過:

HTML:

<input id="myInput" type="text" /> 

JS:

var myInput = document.getElementById('myInput'); 
myInput.setAttribute('custom-attr', 'custom-value'); 
alert(myInput.getAttribute('custom-attr')); 

var myInput = document.getElementById('myInput'); 
var customAttr = document.createAttribute('custom-attr'); 
customAttr.value = 'custom-value'; 
myInput.setAttributeNode(customAttr); 
alert(myInput.getAttribute('custom-attr')); 

在這兩種情況下,IE alert()回報null

+0

我實際上沒有看到第一個代碼被剪斷的問題。在MSIE 6.0和8.0中試過,正確顯示「自定義值」。 –

+0

什麼版本的IE? – epascarello

回答

12

我測試了IE7/8

var myInput = document.getElementById('myInput'); 
myInput.setAttribute('custom-attr', 'custom-value'); 
alert(myInput.getAttribute('custom-attr')); 

你的代碼,它運行良好。這個簡單的測試用例是否會失敗,還是你真的在做一些不同的事情?

您可以使用括號記號

var myInput = document.getElementById('myInput'); 
myInput['custom-attr'] = 'custom-value'; 
alert(myInput['custom-attr']); 

如果你沒有在名稱中-,你可以使用點符號

var myInput = document.getElementById('myInput'); 
myInput.customAttr = 'custom-value'; 
alert(myInput.customAttr); 
+2

那些實際上並不屬性;他們是屬性。 – lonesomeday

+3

有助於在Google上查找更多信息的註釋:此功能被稱爲「expando屬性」。 –

2

你的代碼只是正常的IE6,IE7,IE8 ,FF,Chrome,Opera。