如何在JavaScript中获取选项标签的数据属性 [英] How to get data attribute of option tag in JavaScript
本文介绍了如何在JavaScript中获取选项标签的数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
想从选定的下拉选项中获取数据属性值.
Want to get data attribute value from selected dropdown option.
<select name="selection" id="mySelect">
<option value="21" data-rc="25" data-clnc="10">Treatment</option>
</select>
var rc = ? //value of data-rc
var clnc = ? //value of data-clnc
没有jQuery,请只使用JavaScript:)
No jQuery please only JavaScript :)
推荐答案
您可以通过数据集属性.
var option = document.getElementsByTagName("option")[0];
console.log(option.dataset.rc)
console.log(option.dataset.clnc)
<option value="21" data-rc="25" data-clnc="10">Treatment</option>
或者,如果要获取所选选项的值:
Or, if you want to get the values of the selected option:
var selection = document.getElementById("mySelect");
selection.onchange = function(event){
var rc = event.target.options[event.target.selectedIndex].dataset.rc;
var clnc = event.target.options[event.target.selectedIndex].dataset.clnc;
console.log("rc: " + rc);
console.log("clnc: " + clnc);
};
<select name="selection" id="mySelect">
<option value="21" data-rc="25" data-clnc="10">Treatment</option>
<option value="21" data-rc="23" data-clnc="30">Treatment1</option>
<option value="21" data-rc="31" data-clnc="50">Treatment2</option>
<option value="21" data-rc="14" data-clnc="75">Treatment3</option>
</select>
这篇关于如何在JavaScript中获取选项标签的数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文