JavaScript
function displayContent()
{
var 1 = getElementById(1);
var 2 = getElementById(2);
var 3 = getElementById(3);
var 4 = getElementById(4);
if(document.form.list.selectedIndex==0) {
1.style.display = "block";
}
if(document.form.list.selectedIndex==1) {
2.style.display = "block";
}
if(document.form.list.selectedIndex==2) {
3.style.display = "block";
}
if(document.form.list.selectedIndex==3) {
4.style.display = "block";
}
}
.HTML
<form id="form">
<select onchange="displayContent();" id="list">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</form>
<div id="1">Content1</div>
<div id="2">Content2</div>
<div id="3">Content3</div>
<div id="4">Content4</div>
这是我放在一起的脚本和标记。在此之前,我已经尝试了几种不同的方法,但所有这些方法都会导致相同的非解决方案,就像这个一样。当我更改选择框中的选项时,没有任何反应。我错过了什么吗?
默认情况下,所有div 都设置为 display:none;
。
谢谢乔
你的代码有几个问题,包括getElementById
缺少document.
,没有给你的form
或select
元素一个name
属性,以便你可以在js中引用它们,尝试创建一个以整数开头的变量,并具有以整数开头的id
属性。
考虑到所有这些,请尝试以下操作:
function displayContent() {
var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
var div3 = document.getElementById("div3");
var div4 = document.getElementById("div4");
if(document.form.list.selectedIndex==0) {
div1.style.display = "block";
}
if(document.form.list.selectedIndex==1) {
div2.style.display = "block";
}
if(document.form.list.selectedIndex==2) {
div3.style.display = "block";
}
if(document.form.list.selectedIndex==3) {
div4.style.display = "block";
}
}
示例小提琴
另请注意,这可以大大简化:
function displayContent() {
document.getElementById("div" + (document.form.list.selectedIndex + 1)).style.display = "block";
}
示例小提琴
而不是
getElementById
用
document.getElementById('1');
document.getElementById('2');
document.getElementById('3');
document.getElementById('4');