除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
。