Javascript 如何获取“自定义”的自定义属性;选择权;在触发“后标记”;更改“;事件侦听器?
我的HTML:Javascript 如何获取“自定义”的自定义属性;选择权;在触发“后标记”;更改“;事件侦听器?,javascript,html,Javascript,Html,我的HTML: <select> <option customAttr="foo">Foo Text</option> <option customAttr="bar">Bar Text</option> </select> selectElement.addEventListener("change",function(){ console.log(this.getAttribute("custo
<select>
<option customAttr="foo">Foo Text</option>
<option customAttr="bar">Bar Text</option>
</select>
selectElement.addEventListener("change",function(){
console.log(this.getAttribute("customAttr"));
});
这只记录
null
。为什么?如何使其记录customAttr
的值?您必须以所选选项为目标,如下所示:
var-selectElement=document.querySelector('select');
selectElement.addEventListener(“更改”,函数(){
var option=this.options[this.selectedIndex];
log(option.getAttribute(“customAttr”);
});代码>
富文本
条形文本
您必须针对所选选项,如下所示:
var-selectElement=document.querySelector('select');
selectElement.addEventListener(“更改”,函数(){
var option=this.options[this.selectedIndex];
log(option.getAttribute(“customAttr”);
});代码>
富文本
条形文本
您还可以通过在选项标记中添加值来访问属性,如下所示:
const select=document.getElementById('select');
select.addEventListener(“更改”,(e)=>{
const options=select.querySelectorAll(“选项”);
常数项=e.target.value;
log(选项[item].getAttribute('customAttr'));
});代码>
富文本
条形文本
您还可以通过在选项标记中添加值来访问属性,如下所示:
const select=document.getElementById('select');
select.addEventListener(“更改”,(e)=>{
const options=select.querySelectorAll(“选项”);
常数项=e.target.value;
log(选项[item].getAttribute('customAttr'));
});代码>
富文本
条形文本
看看这是什么。这就是答案。看看这是什么。这就是答案。