设置/获取动态自定义属性

时间:2011-08-29 13:34:07

标签: javascript cross-browser dynamic custom-attributes

主要的现代浏览器支持动态设置/检索自定义属性,IE-family除外。如何在所有浏览器中设置/获取自定义属性?

这是我到目前为止所尝试的:

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

2 个答案:

答案 0 :(得分:17)

我在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);

答案 1 :(得分:3)

您的代码在IE6,IE7,IE8,FF,Chrome,Opera上运行良好。

相关问题