JavaScript:如何使div的样式依赖于选择框中选择的选项?



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.,没有给你的formselect元素一个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');

最新更新