gpt4 book ai didi

javascript - 访问选择列表的选项时获取 "null or not an object error"

转载 作者:行者123 更新时间:2023-11-30 18:06:19 25 4
gpt4 key购买 nike

当我尝试用 javascript 编写代码时,我似乎一遍又一遍地收到此 null or not an object 错误。这是一个简单的例子,我只是想弹出一个显示选项名称的窗口。我在编码时如何避免出现此错误?

代码在 Internet Explorer 中返回此错误:

Error: 'document.forms.0.questions' is null or not an object

<!DOCTYPE html>
<!-- HTML5 style -->
<head>
<title>Challenge Question</title>
<script type="text/javascript">
/* <![CDATA[ */
window.alert(document.forms[0].questions.pet.name);
/* ]]> */
</script>
</head>
<body>
<form action="get" >
<select name="questions">
<option value="pet" name="pet">What is your pet's name?</option>
</select>
</form>
</body>
</html>

最佳答案

必须先将元素添加到 DOM 中,然后才能访问它。现在您正在尝试访问一个尚不存在的元素:

<!DOCTYPE html>
<html>

<head>
<title>Challenge Question</title>
</head>
<body>
<form action="get">
<select name="questions">
<!-- Element is added here -->
<option value="pet" name="pet">What is your pet's name?</option>
</select>
</form>
<script type="text/javascript">
/* and can be accessed here, after it's added */
console.log(document.forms[0].questions.options['pet']);
</script>
</body>

</html>

FIDDLE

关于javascript - 访问选择列表的选项时获取 "null or not an object error",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15726929/

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