繁体   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