我打算使用这段代码:
HTML :
<select id="myDropdown">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
和 javascript :
document.getElementById("myDropdown").selectedIndex = -1;
但我不知道如何在我的页面中实现这一点 这就是我目前的方式。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" type="text/javascript">
document.getElementById("myDropdown").selectedIndex = -1;
</script>
<title>Untitled Document</title>
</head>
<body>
<select id="myDropdown">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</body>
</html>
我想这样做,以便当他们进入页面时有一个空白选择,但他们看不到空选项。为什么这不起作用?
答案 0 :(得分:2)
您的脚本位于<head>
,在DOM准备就绪之前触发,将其移至<body>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<select id="myDropdown">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
<script language="javascript" type="text/javascript">
document.getElementById("myDropdown").selectedIndex = -1;
</script>
</body>
</html>