繁体   English   中英

如何在 JavaScript 中获取选项标签的数据属性

[英]How to get data attribute of option tag in JavaScript

想要从选定的下拉选项中获取数据属性值。

<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 :)

您可以通过dataset 属性读取它们。

 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>

或者,如果您想获取所选选项的值:

 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>

假设我们有一个选择字段

    <select id="ddlViewBy">
      <option value="1" data-rc="25" data-clnc="10" selected="selected">test1</option>
      <option value="2" >test2</option>
      <option value="3">test3</option>
    </select>

现在我们将获得选择列表及其选择的选项

    var e = document.getElementById("ddlViewBy");
    var option= e.options[e.selectedIndex];

现在我们有了选择的选项,我们可以得到它的属性

    var attrs = option.attributes;

attrs 是属性数组,您可以通过所需的索引获取属性。

或者你可以通过

    var datarc = option.getAttribute("data-rc");

检查这支工作笔

工作笔

$('#options').on('change', function(){
    alert($(this).find("option:selected").attr('data-rc'))
    alert($(this).find("option:selected").attr('data-clnc'))
});

 var mySelect = document.querySelector('#mySelect') console.log('mySelect value ' + mySelect.value) console.log('mySelect data-rc ' + mySelect.selectedOptions[0].getAttribute("data-rc")) console.log('mySelect data-clnc ' + mySelect.selectedOptions[0].getAttribute("data-clnc"))
 <select name="selection" id="mySelect"> <option value="21" data-rc="25" data-clnc="10">Treatment</option> </select>

你可以用 jquery 选择器做到这一点

var rc = $('select option:selected').data('rc');

$(selector).find("option:selected").data("rc") 用于 rc 和 clnc 用于 clnc 其中选择器是您的“选择”标签 ID/类

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM