繁体   English   中英

触发“更改”事件侦听器后,如何获取“选项”标签的自定义属性?

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

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