我的 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>
关于javascript - 如何在触发 "option"事件监听器后获取 "change"标记的自定义属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48454359/