[英]Read data attribute from select using native javascript
Problem is simple, I found some answers using jquery but none in native JS. 问题很简单,我使用jquery找到了一些答案,但是在本机JS中却找不到答案。
Not able to read the value of label, it should work in IE8+ 无法读取标签的值,它应该可以在IE8 +中使用
var select = document.getElementById('test');
select.onchange = function() {
//Value works fine
//alert(select.options[0].value);
//How can I read data attribute?
alert(select.options[0].data-label);
}
HTML: HTML:
<select id="test">
<option data-label="label-1" value="HK">Hong Kong</option>
<option data-label="label-2" value="CH">China</option>
</select>
Because there is no native getData, you need to just say 因为没有本地的getData,所以您只需要说
getAttribute("data-label");
https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttribute https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttribute
The newer version of this (check browser support! IE 11!) 的较新版本(请检查浏览器支持!IE 11!)
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
element.dataset.label
You can use getAttribute
. 您可以使用getAttribute
。
Like this: 像这样:
alert(select.options[0].getAttribute('data-label'));
Demo: http://jsfiddle.net/Lnybn/1/ 演示: http : //jsfiddle.net/Lnybn/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.