![](/img/trans.png)
[英]How do I change the “selected” attribute on an option tag with javascript
[英]How do I get the custom attribute of an “option” tag after firing the “change” event listener?
我的HTML:
<select>
<option customAttr="foo">Foo Text</option>
<option customAttr="bar">Bar Text</option>
</select>
我的JS:
selectElement.addEventListener("change",function(){
console.log(this.getAttribute("customAttr"));
});
这仅记录null
。 为什么? 如何使其记录customAttr
的值?
您必须将选定的选项作为目标,如下所示:
var selectElement = document.querySelector('select'); selectElement.addEventListener("change",function(){ var option = this.options[this.selectedIndex]; console.log(option.getAttribute("customAttr")); });
<select> <option customAttr="foo">Foo Text</option> <option customAttr="bar">Bar Text</option> </select>
您还可以通过在选项标签中添加值来访问属性,如下所示:
const select = document.getElementById('select'); select.addEventListener("change", (e) => { const options = select.querySelectorAll("option"); const item = e.target.value; console.log(options[item].getAttribute('customAttr')); });
<select id='select'> <option value='0' customAttr="foo">Foo Text</option> <option value='1' customAttr="bar">Bar Text</option> </select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.