代码之家  ›  专栏  ›  技术社区  ›  abatishchev Karl Johan

重构链接以显示/隐藏表行

  •  2
  • abatishchev Karl Johan  · 技术社区  · 14 年前

    我有一张带驾驶室的桌子,用户可以把它藏起来。它是这样实现的:

    Markup:

    <table>
       <tr>
          <td>
             <table style="margin-left: auto; text-align: right;">
                <tr>
                   <td class="stats-hide">
                      <a href="#" onclick="hideStats();">Hide</a>
                   </td>
                   <td class="stats-show" style="display: none;">
                      <a href="#" onclick="showStats();">Show</a>
                   </td>
                </tr>
             </table>
          </td>
       </tr>
       <tr class="stats-hide">
          <td>
            <!-- data -->
          </td>
       </tr>
    </table>
    

    和jquery代码:

    <script type="text/javascript" language="javascript">
        function hideStats() {
            hideControls(true, $('.stats-hide'));
            hideControls(false, $('.stats-show'));
        }
    
        function showStats() {
            hideControls(false, $('.stats-hide'));
            hideControls(true, $('.stats-show'));
        }
    
        function hideControls(value, arr) {
            $(arr).each(function () {
                if (value) {
                    $(this).hide();
                }
                else {
                    $(this).show();
                }
            });
     }
    </script>
    

    如何用一个、单个链接和一个(可能是)CSS类实现相同的行为?

    我的想法-将一个布尔变量存储在某个地方,并切换控件相对于该变量的可见性。还有吗?

    3 回复  |  直到 14 年前
        1
  •  2
  •   Anurag    14 年前

    在IE上隐藏的行是否工作不正常?jquery和浏览器的版本是什么,这很麻烦?

    我创造了一个 example 按照@galen的建议使用toggle,它可以在chrome、firefox和safari上工作。我没有IE。

    代码如下:

    HTML

    <table>
       <tr>
          <td>
             <table class="data">
                <tr>
                   <td class="stats-hide">
                      <a href="#" class="toggle-stats">Hide</a>
                   </td>
                   <td class="stats-show">
                      <a href="#" class="toggle-stats">Show</a>
                   </td>
                </tr>
             </table>
          </td>
       </tr>
       <tr class="stats-hide">
          <td>
            Some Data
          </td>
       </tr>
    </table>
    

    JavaScript

    $(".toggle-stats").click(function() {
        $(".stats-hide, .stats-show").toggle();
    });
    ​
    
        2
  •  2
  •   rajasaur    14 年前

    使用上面提到的切换,但是使用“tbody”而不是“tr”,这样可以根据需要隐藏/显示行。

        3
  •  1
  •   Galen    14 年前

    您可以使用jquery的 toggle 在隐藏和显示对象之间交替使用一个链接。您不需要存储任何变量。