此代码旨在显示和隐藏基于按钮单击的表格,但是,它似乎无法正确切换。有谁知道我做错了什么?
<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 :(得分:2)
您的标记无效,您需要将表格放在正文
中<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
答案 1 :(得分:0)
在你的代码中: var status = document.getElementById(“modelTable”)。style.display; if(status =='block'){ 。的document.getElementById( “modelTable”)的style.display = “无”; } else { 的document.getElementById( “modelTable”)的style.display = “块”。 }
使用css可能更好:
css: .hide {display:none; }
javascript: 的document.getElementById( 'modelTable')classList.toggle( '隐藏');