2010-05-29 56 views
0

我使用此javascript在選擇時顯示不同的div類。我需要的,如果什麼也沒有選擇,例如,當加載頁面時顯示一個DIV類,以及與根據選擇的div的一個取代它......如果沒有選擇任何內容,則顯示一個div

<script type="text/javascript"><!-- 
    var lastDiv = ""; 
    function showDiv(divName) { 
    // hide last div 
    if (lastDiv) { 
     document.getElementById(lastDiv).className = "hiddenDiv"; 
    } 
    //if value of the box is not nothing and an object with that name exists, then change the class 
    if (divName && document.getElementById(divName)) { 
     document.getElementById(divName).className = "visibleDiv"; 
     lastDiv = divName; 
    } 
} 
//--> 
    </script> 

CSS:

<style type="text/css" media="screen"><!-- 
    .hiddenDiv { 
    display: none; 
    } 
    .visibleDiv { 
    display: block; 
    border: 1px grey solid; 
    } 

    --></style> 

HTML:

<form id="FormName" action="blah.php" method="get" name="FormName"> 
     <select name="selectName" size="1" onChange="showDiv(this.value);"> 
      <option value="">Choose One...</option> 
      <option value="one">first</option> 
      <option value="two">second</option> 
      <option value="three">third</option> 
     </select> 
    </form> 
    <p id="one" class="hiddenDiv">This is paragraph 1.</p> 
    <p id="two" class="hiddenDiv">This is paragraph 2.</p> 
    <p id="three" class="hiddenDiv">This is paragraph 3.</p> 

任何人都可以幫忙嗎?

回答

0
<select onChange="showDiv(this.value);"> 

<select>元件不具有value屬性。該值位於<option>兒童。要獲得<select>元素的當前選擇的選項的值時,您需要滿足以下條件:

var selected = dropdown.options[dropdown.selectedIndex].value; 

所以你onchange調用需要進行如下改變:

<select onchange="showDiv(this.options[this.selectedIndex].value);"> 

這就是說, onchange屬性應拼寫全部小寫,而段落不是div。

0

給ID選擇列表

<select name="selectName" id="selectName" size="1" onChange="showDiv(this.value);"> 

通話的window.onload功能

window.onload =function(){ 
     showDiv(document.getElementById("selectName").value); 
} 
相關問題