未定义的选项名称 javascript

Undefined option name javascript

本文关键字:javascript 选项 未定义      更新时间:2023-09-26

我有以下代码。但警报不显示选项的名称,而是显示"未定义"。对于值,它显示正确的内容。

<select id="test" name="select_decision" onchange="javascript:
var activeText = this.options[this.selectedIndex].value
var activeOption = this.options[this.selectedIndex].name;
alert(activeOption);
">

一个选项的示例是:

<option value="test" name="test_name">Test</option>

一直在谷歌上寻找答案,但找不到!

option 元素没有 name 属性,因此它没有反射属性,因此optionElement.name undefined

虽然您可以通过 optionElement.getAttribute("name") 获取该属性的值,但通常,如果要向元素添加自定义属性,则应使用 data-* 前缀。

尝试使用 htmlElement.getAttribute(attrName)。因此,在您的情况下,请尝试使用

var activeOption = this.options[this.selectedIndex].getAttribute('name');

而不是你的

var activeOption = this.options[this.selectedIndex].name;