0

我有一个带有折叠表的简单菜单,使用 Javascript。我的问题是当我在浏览器中打开它时,所有表格都已经折叠了!如何在菜单部分“关闭”的情况下打开它,然后仅在单击时折叠每个部分?我知道它在 Javascript 中,但我是新手,所以请耐心等待...谢谢!

这是基本代码:

<head>
<script>
function doCollapse(rowname)
{
theElement = document.getElementById(rowname);
if(theElement.style.display == 'none'){
theElement.style.display = '';
}else {
theElement.style.display = 'none';
}
return false;
}
</script>
</head>


<body>
<table>
<tr>
  <td>
    <p1 onClick=" doCollapse ('r1');">JQ</p>
  </td></tr>
<tr>
  <td id="r1">ver biografia</td></tr>

<tr>
  <td>
   <p2 onClick=" doCollapse ('r2');">Obras</p>
 </td>
</tr>
<tr>
<td id="r2">lista</td></tr>

<tr>
  <td>
 <p3 onClick=" doCollapse ('r3');">Exposições</p>
  </td>
</tr>
<tr>
  <td id="r3">lista</td></tr>

</table>
</body>
</code>
4

1 回答 1

0

Since you are using pure javascript and not a library like jquery, I'd suggest a couple of modification to easily target your elements. Try to put the items to show and hide inside a span so you can use document.getElementsByTagName and then add the Id to those spans rather than on td. My concern was that you have more td in your code, so you using document.getElementsByTagName would affect them as well, which is not what you need. However, you need to be careful that my solution would also suffer from that side effect if you have more spans in your code, which is likely, so you need to take this consideration before you implement this live. Here is the code and you can see a live demo here

<head>
<script>
    function init(){
        var numberOfRows = document.getElementsByTagName('span').length;
        for (var i = 0; i < numberOfRows; i++){
       document.getElementsByTagName('span')[i].style.display = 'none';
        }

    }

function doCollapse(rowname)
{
theElement = document.getElementById(rowname);
if(theElement.style.display == 'none'){
theElement.style.display = 'inline';
}else {
theElement.style.display = 'none';
}
return false;
}
</script>
</head>


<body onload="init()">
<table>
<tr>
  <td>
    <p onClick=" doCollapse ('r1');">JQ</p>
  </td></tr>
<tr>
    <td><span id="r1">ver biografia</span></td></tr>

<tr>
  <td>
   <p onClick=" doCollapse ('r2');">Obras</p>
 </td>
</tr>
<tr>
<td><span id="r2">lista</span></td></tr>

<tr>
  <td>
 <p onClick=" doCollapse ('r3');">Exposições</p>
  </td>
</tr>
<tr>
    <td><span id="r3">lista</span></td></tr>

</table>
于 2012-09-30T20:11:58.777 回答