您在上面给出的答案有效,但令人困惑,因为您两次使用了两个名称并且您有不必要的代码行。你正在做一个不必要的过程。
在调试代码时用笔和纸绘制小框来表示内存空间(即存储的变量)然后绘制箭头来指示变量何时进入小框以及何时出来,这是一个好主意,如果它被覆盖或被复制等。
如果您使用下面的代码执行此操作,您会看到
var selectBox = document.getElementById("selectBox");
被放在一个盒子里,然后你就不会用它做任何事情。
和
var selectBox = document.getElementById("selectBox");
当你有一个 selectBox 的选择 id 作为选项列表时,很难调试并且令人困惑。 ----您要操作/查询/等哪个selectBox是会消失的本地var selectBox还是您分配给select标签的selectBox id
在您添加或修改代码之前,您的代码可以正常工作,然后您就可以轻松跟踪并搞混
<html>
<head>
<script type="text/javascript">
function changeFunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
一种更精简的方法也是:
<html>
<head>
<script type="text/javascript">
function changeFunc() {
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
使用与您正在处理的程序和任务相匹配的描述性名称是一个好主意,目前正在编写一个类似的程序来使用您的代码接受和处理邮政编码,并使用描述性名称对其进行修改,目标是使计算机语言为尽可能接近自然语言。
<script type="text/javascript">
function Mapit(){
var actualPostcode=getPostcodes.options[getPostcodes.selectedIndex].value;
alert(actualPostcode);
// alert is for debugging only next we go on to process and do something
// in this developing program it will placing markers on a map
}
</script>
<select id="getPostcodes" onchange="Mapit();">
<option>London North Inner</option>
<option>N1</option>
<option>London North Outer</option>
<option>N2</option>
<option>N3</option>
<option>N4</option>
// a lot more options follow
// with text in options to divide into areas and nothing will happen
// if visitor clicks on the text function Mapit() will ignore
// all clicks on the divider text inserted into option boxes
</select>