Javascript 动态设置/获取自定义属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7230851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
set/get dynamically custom attribute
提问by ritmas
Major modern browsers support setting/retrieving custom attribute dynamically, except IE-family. How can I set/get my custom attribute in all browsers?
现代主流浏览器支持动态设置/检索自定义属性,IE 系列除外。如何在所有浏览器中设置/获取我的自定义属性?
This is what I've tried so far:
这是我迄今为止尝试过的:
HTML:
HTML:
<input id="myInput" type="text" />
JS:
JS:
var myInput = document.getElementById('myInput');
myInput.setAttribute('custom-attr', 'custom-value');
alert(myInput.getAttribute('custom-attr'));
or
或者
var myInput = document.getElementById('myInput');
var customAttr = document.createAttribute('custom-attr');
customAttr.value = 'custom-value';
myInput.setAttributeNode(customAttr);
alert(myInput.getAttribute('custom-attr'));
In both cases IE alert()
returns null
.
在这两种情况下,IE 都会alert()
返回null
.
回答by epascarello
I tested your code on IE7/8
我在 IE7/8 上测试了你的代码
var myInput = document.getElementById('myInput');
myInput.setAttribute('custom-attr', 'custom-value');
alert(myInput.getAttribute('custom-attr'));
and it runs fine. Does that simple test case fail for you, or are you actually doing something different?
它运行良好。那个简单的测试用例对您来说是否失败,或者您实际上在做一些不同的事情?
You can use bracket notation
您可以使用括号表示法
var myInput = document.getElementById('myInput');
myInput['custom-attr'] = 'custom-value';
alert(myInput['custom-attr']);
If you did not have the -
in the name, you can use dot notation
如果-
名称中没有 ,则可以使用点表示法
var myInput = document.getElementById('myInput');
myInput.customAttr = 'custom-value';
alert(myInput.customAttr);
回答by Paktas
Your code works just fine on IE6, IE7, IE8, FF, Chrome, Opera.
您的代码在 IE6、IE7、IE8、FF、Chrome、Opera 上运行良好。