2012-05-21 61 views
1

的JavaScriptJavaScript:如何根据选择框中选择的选项制作div的样式?

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;

感谢, 乔

+0

你的ID应该以字母开头,而不是数字 – jbabey

回答

0

,而不是

getElementById 

使用

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

有几个问题与您的代码,包括来自getElementById缺少document.,不给你formselect元素一个name属性,所以你可以参考th em在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

+0

+1“大规模简化”。 – karim79

相关问题