问题很简单,我使用 jquery 找到了一些答案,但在原生 JS 中没有找到答案。
无法读取标签的值,在 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:
<select id="test">
<option data-label="label-1" value="HK">Hong Kong</option>
<option data-label="label-2" value="CH">China</option>
</select>
最佳答案
因为没有原生的 getData,所以你只需说
getAttribute("data-label");
https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttribute
此版本的较新版本(检查浏览器支持!IE 11!)
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
element.dataset.label
关于javascript - 使用 native JavaScript 从 select 读取数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22742880/