ome*_*ega 32 html javascript select
如果我有这个代码:
<select onchange="alert('?');" name="myname" class="myclass">
<option isred="-1" value="hi">click</option>
</select>
Run Code Online (Sandbox Code Playgroud)
如何从自定义属性isred中获取值"-1"?我不想使用value属性.而且我不希望通过名称或ID来定位选项标记.
我想要类似的东西 onchange="alert(this.getselectedoptionID.getAttribute('isred'));"
有人可以帮忙吗?
另外我不想使用jquery.
Mar*_*.io 56
您需要弄清楚selectedIndex是什么,然后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>?????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)
不要在你的内容中使用内联javascriptHTML.您希望将业务逻辑与UI分开.创建一个javascript事件处理程序来处理这个问题.(jQuery/Angular/etc)
小智 18
在jquery中,你可以写:
$("#myname").find(':selected').attr('isred');
Run Code Online (Sandbox Code Playgroud)
使用这样的东西:
document.getElementById("x").onchange = function () {
console.log(this.options[this.selectedIndex].getAttribute("isred"));
};
Run Code Online (Sandbox Code Playgroud)
//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)
}Run Code Online (Sandbox Code Playgroud)
<select id="name_your_id" name="myname" class="myclass">
<option isred="423423" value="hi">One</option>
<option isred="-1" value="hi">Two</option>
</select>Run Code Online (Sandbox Code Playgroud)