1

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

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

错误:“ document.forms.0.questions”是null或不是对象

<!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>
4

2 回答 2

2

必须先将元素添加到 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>

小提琴

于 2013-03-31T06:19:47.727 回答
0

我已经测试了代码。它工作正常。

<script type="text/javascript">
 function func1()
  {
    var index = document.getElementById("pet").selectedIndex;
    var value = document.getElementById("pet").options[index].text;
    alert(value);
  }

 <form action="get">
 <select name="questions" id="pet" onchange="if (this.selectedIndex) func1();">
    <!-- Element is added here -->
    <option value="pet" name="pet"  >What is your pet's name?</option>
     <option value="pet" name="pet"  >What is your pet's 1?</option>
  </select>
  </form>
于 2013-03-31T06:33:21.250 回答