2013-11-28 171 views
0

此代碼旨在顯示和隱藏基於點擊按鈕的表格,但是,它似乎無法正確切換。有誰知道我做錯了什麼?OnClick事件表不會正確觸發

<body> 
    <br> 
     <button onclick="toggleTable();" style="position:absolute; top:130px; left:1000; width:200px; height:25px">3-D Model</button> 

    <br> 
</body> 

<script> 

    function toggleTable() 
{ 

var status = document.getElementById("modelTable").style.display; 

if (status == 'block') { 
    document.getElementById("modelTable").style.display="none"; 
} else { 
    document.getElementById("modelTable").style.display="block"; 
} 
} 

    <table id="modelTable" border="1" align="right" style="display:block; position:absolute; top:150px; left:1000;"> 
     <tr> 
      <th> 
       <a href="google.com"> 3-D Model </a> 
      </th> 
     </tr> 
     <tr> 
      <td> 
       <a>test1</a> 

      </td> 
     </tr> 
     <tr> 
      <td> 
       <a>test2</a> 
      </td> 
     </tr> 
    </table> 

</script> 
+0

您的標記無效,您需要將標籤放在主體內 –

+0

'Java'是'JavaScript','Car'是'Carpet'。 –

回答

2

您marksup是無效的,你需要把身體內的TABEL

<body> 
    <br/> 
    <button onclick="toggleTable();" style="position:absolute; top:130px; left:1000; width:200px; height:25px">3-D Model</button> 
    <br/> 
    <table id="modelTable" border="1" align="right" style="display:block; position:absolute; top:150px; left:1000;"> 
     <tr> 
      <th> <a href="google.com"> 3-D Model </a> 

      </th> 
     </tr> 
     <tr> 
      <td> <a>test1</a> 

      </td> 
     </tr> 
     <tr> 
      <td> <a>test2</a> 

      </td> 
     </tr> 
    </table> 
    <script> 
     function toggleTable() { 
      var table = document.getElementById("modelTable"); 
      var status = table.style.display; 
      if (status == 'block') { 
       table.style.display = "none"; 
      } else { 
       table.style.display = "block"; 
      } 
     } 
    </script> 
</body> 

演示:Fiddle

0

在您的代碼: VAR狀態=的document.getElementById( 「modelTable」) .style.display; (status =='block'){ document.getElementById(「modelTable」)。style.display =「none」; if(status =='block'){ document.getElementById } else { document.getElementById(「modelTable」).style.display =「block」; }

它可能是更好的使用CSS:

的CSS: .hide {顯示:無; }

javascript: document.getElementById('modelTable')。classList.toggle('hide');