您在上面给出的答案有效,但令人困惑,因为您使用了两个名称两次,并且有一行不必要的代码。你正在做一个不必要的过程。
在调试代码时,用笔和纸画小盒子来表示内存空间(即存储的变量),然后画箭头来指示变量何时进入小盒子以及何时出现,这是一个好主意覆盖或复制等。
如果您使用下面的代码执行此操作,您将看到
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>