[英]How do I get the custom attribute value of an element using javascript
How do I get the name value from the following? 如何从以下内容中获取名称值?
<select id="product">
<option name="name1" value="1">one</option>
<option name="name2" value="2">two</option>
</select>
I tried this (adding .name to the end. .value works, .name doesn't) 我尝试了此操作(将.name添加到末尾。.value起作用,.name不起作用)
var select = document.getElementById("product");
select.onchange = function(){
var selectedString = select.options[select.selectedIndex].name;
alert(selectedString);
}
thanks 谢谢
Use getAttribute
because name
is not a valid attribute for option (so there is no name
property for the option element which gets updated when you set its name
attribute), hence you cannot get it from the name
property (by accessing elm.name
). 使用
getAttribute
是因为name
不是选项的有效属性(因此,对于option元素,没有name
属性,当您设置其name
属性时会对其进行更新),因此无法通过name
属性(通过访问elm.name
)来获取elm.name
。
var selectedString = this.options[this.selectedIndex].getAttribute('name');
Better way would be to make it a data-*
attribute and access it using dataset (Not supported in older browser versions). 更好的方法是将其设为
data-*
属性,然后使用数据集进行访问(在旧版浏览器中不支持)。
<select name="model" id="model">
<option data-name="name1" value="1">one</option>
<option data-name="name2" value="2">two</option>
</select>
and 和
this.options[this.selectedIndex].dataset.name; //or this.options[this.selectedIndex].getAttribute('data-name')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.