JavaScript代码有错,麻烦大侠调一下。

来源:百度知道 编辑:UC知道 时间:2024/06/07 23:41:18
<html>
<head>
<script type="text/javascript">
function getOptions()
{
var x=document.getElementById("mySelect");
for (i=0; i<x.length; i++)
{
document.write(x.options[i].text);
document.write("<br />")
}
}
</script>
</head>
<body>

<form>
Select your favorite fruit:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
<br /><br />
<input type="button" onclick="getOptions()" value="Output all options">
</form>

</body>
</html>
怎么看怎么觉得没错,可它就是不出来

当你执行第一个document.write()的时候 , 页面已经被改写,这时候 <select id="mySelect"> 已经不存在了,所以你的程序会出错。

<html>
<head>
<script type="text/javascript">
function getOptions()
{
var x=document.getElementById("mySelect");
var selectStr = "";
for (i=0; i<x.length; i++)
{
selectStr += x.options[i].text + "<br>";

}
document.write(selectStr);
}
</script>
</head>
<body>

<form>
Select your favorite fruit:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
<br /><br />
<input type="button" onclick="getOptions()" value="Output all options">
</form