39

如果我有这个代码:

 <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。

4

7 回答 7

73

您需要弄清楚 selectedIndex 是什么,然后getAttribute从该 options[] 数组中找出。

<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 演示

作为旁注:

不要在你的HTML. 您希望将业务逻辑与 UI 分开。而是创建一个 javascript 事件处理程序来处理此问题。(jQuery / 角度 / 等)

于 2012-08-14T17:38:55.060 回答
30

在 jquery 中,你可以写:

$("#myname").find(':selected').attr('isred');
于 2013-11-12T13:45:31.167 回答
8

使用这样的东西:

document.getElementById("x").onchange = function () {
    console.log(this.options[this.selectedIndex].getAttribute("isred"));
};
于 2012-08-14T17:38:21.607 回答
3

假设我们有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
}

演示

于 2015-07-01T21:51:59.383 回答
2

//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>

于 2019-05-03T09:38:09.913 回答
1

你用:.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>
于 2012-08-14T17:35:50.867 回答
-1

你可以

$(".myclass").val(function(){alert($("option",this).attr("isred"));})
于 2013-10-05T06:28:15.393 回答