简体   繁体   English

如何使用javascript获取元素的自定义属性值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM