未捕获类型错误:不能读取属性'text'在Java脚本中获取所选值的未定义

Uncaught TypeError: Cannot read property 'text' of undefined for getting selected value in java script

本文关键字:获取 脚本 Java 未定义 text 不能读 不能 错误 读取 属性 类型      更新时间:2023-09-26

我试图从下拉值中获得所选值,在警告中显示

Uncaught TypeError: Cannot read property 'text' of undefined

有人能帮我吗?
var selectedObj = document.getElementById('selectedOption');
alert("selectedObj--->"+selectedObj);
var selectedOptionText = selectedObj.options[selectedObj.selectedIndex].text;

selectedIndex

技术细节

返回值:一个数字,表示的索引下拉列表中选择的选项。索引从0开始。如果未选择选项,返回值为-1

因此,如果没有选择任何选项,您最终将得到selectedObj.options[-1],它将始终是undefined

你可以这样写:

var selectedOptionText = selectedObj.selectedIndex > -1 ? selectedObj.options[selectedObj.selectedIndex].text : null;

如果不选择任何选项,则selectedOptionText为空。

var selectedIndex = selectedObj.selectedIndex;
if (selectedIndex === -1) selectedIndex = 0;
var selectedOptionText = selectedObj.options[selectedIndex].text;

如果您希望selectedOptionText在未选择选项的情况下等于select的第一个选项

你期望'selectedObj'是什么?HTML选项元素还是选择元素?这在代码中是不明确的…

selectedObj.options

暗示它是select元素,

也是
selectedObj.selectedIndex

,

var selectedObj = document.getElementById('selectedOption');

暗示这是一个HTML选项元素。

你需要检查:

console.log(selectedObj.tagName)

注意使用console.log()是一个比alert()更容易调试的选项。