gpt4 book ai didi

javascript - 如何在触发 "option"事件监听器后获取 "change"标记的自定义属性?

转载 作者:行者123 更新时间:2023-11-28 17:38:47 25 4
gpt4 key购买 nike

我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com