Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何获取“自定义”的自定义属性;选择权;在触发“后标记”;更改“;事件侦听器?_Javascript_Html - Fatal编程技术网

Javascript 如何获取“自定义”的自定义属性;选择权;在触发“后标记”;更改“;事件侦听器?

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

我的HTML:

<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'));
});

富文本
条形文本

看看这是什么。这就是答案。看看这是什么。这就是答案。