![](/img/trans.png)
[英]How do I change the “selected” attribute on an option tag with 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.