簡體   English   中英

html - 如何在下拉列表中獲取選項標簽的自定義屬性?

[英]html - how to get custom attribute of option tag in dropdown?

如果我有這個代碼:

 <select onchange="alert('?');" name="myname" class="myclass"> 
    <option isred="-1" value="hi">click</option>
 </select>

如何從自定義屬性isred中獲取值“-1”? 我不想使用value屬性。 而且我不希望通過名稱或ID來定位選項標記。

我想要像onchange="alert(this.getselectedoptionID.getAttribute('isred'));"

有人可以幫忙嗎?

另外我不想使用jquery。

您需要確定selectedIndex是什么,然后從那些options [] Array中找出getAttribute

<select onchange="alert(this.options[this.selectedIndex].getAttribute('isred'));" name="myname" class="myclass"> 
    <option isred="-1" value="hi">click</option>
    <option isred="-5" value="hi">click</option>
</select>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

jsFiddle DEMO

作為旁注:

不要HTML 使用內聯JavaScript 您希望將業務邏輯與UI分開。 創建一個javascript事件處理程序來處理這個問題。 (jQuery / Angular / etc)

在jquery中,你可以寫:

$("#myname").find(':selected').attr('isred');

使用這樣的東西:

document.getElementById("x").onchange = function () {
    console.log(this.options[this.selectedIndex].getAttribute("isred"));
};

假設我們有一個HTML標記如下:

<form id="frm_">
    <select name="Veh">
        <option value='-1' selected='selected'>Select</option>
        <option value='0' ren='x'>xxx</option>
        <option value='1' ren='y'>yyy</option>
    </select>
</form>

可以像這樣訪問attr "ren"

function getRep() {
    var ren = document.forms['frm_'].elements['Veh'].options[document.forms['frm_']
                 .elements['Veh'].selectedIndex].getAttribute('ren');
    console.log("Val of ren " + ren); //x or y
}

演示

您使用: .getAttribute('isred')

你要:

<select onchange="alert(this.options[this.selectedIndex].getAttribute('isred'));" name="myname" class="myclass">
    <option isred="-1" value="hi">click</option>
    <option isred="-1" value="ho">click</option>
</select>

 //Pure Javascript solution, and elegant one check if you really want to leverage the power of javascript. // Listening to a onchange event by ID attached with the select tag. document.getElementById("name_your_id").onchange = function(event) { //event.target.selectedOptions[0] have that option. as this is single selection by dropdown. this will always be 0th index :) let get_val = event.target.selectedOptions[0].getAttribute("isred"); console.log("Value from the Attribute: ", get_val) } 
  <select id="name_your_id" name="myname" class="myclass"> <option isred="423423" value="hi">One</option> <option isred="-1" value="hi">Two</option> </select> 

您可以

$(".myclass").val(function(){alert($("option",this).attr("isred"));})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM