JavaScript:如何根据选择框中选择的选项创建div的样式?

时间:2012-05-21 12:56:10

标签: javascript html forms

的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;

谢谢, 乔

2 个答案:

答案 0 :(得分:2)

您的代码存在多个问题,包括document.中缺少getElementById,未向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";
    }
}

Example fiddle


另请注意,这可以大规模简化:

function displayContent() {
    document.getElementById("div" + (document.form.list.selectedIndex + 1)).style.display = "block";
} 

Example fiddle

答案 1 :(得分:0)

而不是

getElementById

使用

document.getElementById('1');
document.getElementById('2');
document.getElementById('3');
document.getElementById('4');