我编写此代码示例代码以隐藏2行但它不起作用

时间:2013-02-04 15:01:26

标签: javascript html css

我试图隐藏两行<tr><td>line 1</td></tr><tr><td>line 2</td></tr>,将它们包装在设置了display:none的div中,但这些行不会被隐藏。为什么呢?

<script type="text/javascript">
  function toggle() {
    var ele = document.getElementById("toggleText");
    var text = document.getElementById("displayText");
    if(ele.style.display == "block") {
      ele.style.display = "none";
      text.innerHTML = "Show";
    } else {
      ele.style.display = "block";
      text.innerHTML = "Hide";
    }
  } 
</script>

<table>
  <tr>
    <td>
      <a id="displayText" href="javascript:toggle();">Show</a>
    </td>
  </tr>

  <div id="toggleText" style="display: none;">
    <tr><td>line 1</td></tr>
    <tr><td>line 2</td></tr>
  </div>
</table>

2 个答案:

答案 0 :(得分:3)

您的HTML标记无效,您不能将div作为表格中的子元素!

答案 1 :(得分:1)

当你想在表格中放置div时,它需要存在于表格单元格内部,这意味着在td内部。注意我按类名选择了两个div,因为id是唯一的。

<script language="javascript"> 
 function toggle() {
    var ele = document.getElementsByClassName("toggleText");
    var text = document.getElementById("displayText");
    if(ele[0].style.display == "block") {
        ele[0].style.display = "none";
        ele[1].style.display = "none";
        text.innerHTML = "Show";
    }
    else {
        ele[0].style.display = "block";
        ele[1].style.display = "block";
        text.innerHTML = "Hide";
    }
} 
</script>
<table>

    <tr><td>
    <a id="displayText" href="javascript:toggle();">Show</a>
    </td></tr>

    <tr><td><div class="toggleText">line 1</div></td></tr>
    <tr><td><div class="toggleText">line 2</div></td></tr>

</table>