代码之家  ›  专栏  ›  技术社区  ›  mare

如何通过单击链接以编程方式显示和隐藏DIV?

  •  0
  • mare  · 技术社区  · 15 年前

    2) 单击语句链接后切换隐藏/取消隐藏的最简单方法是什么?第一次单击应该显示DIV(取消隐藏),第二次单击应该隐藏它,依此类推。

    <a>Statement</a>
    <div id="taxStatement">insert select statement dropdownbox</div>
    
    3 回复  |  直到 15 年前
        1
  •  3
  •   Nick Craver    15 年前

    可以为链接提供一个类,例如:

    <a class="toggle" href="#">Statement</a>
    <div id="taxStatement">insert select statement dropdownbox</div>
    

    document.ready 具有 .click() .toggle() 元素,如下所示:

    $(function() {
      $("a.toggle").click(function(e) {
        $(this).next().toggle();
        e.preventDefault();
      });
    });
    

    您可以先隐藏 <div> 通过多种方式,CSS:

    #taxStatement { display: none; }
    

    或者给它上课。 class="toggleDiv" 把它们都藏起来:

    .toggleDiv { display: none; }
    

    或者在你的 ,通过脚本:

    $(".toggleDiv").hide();
    

    You can give it a try/experiment here .

        2
  •  1
  •   JasCav    15 年前

    对于问题1和2,您需要使用切换:

    $('a').toggle(
    function () {
      // Unhide Statement
      $('#taxStatement').show();
    },
    function () {
      $('#taxStatement').hide();
    });
    
        3
  •  0
  •   kennytm    15 年前
       var theDiv = $('#taxStatement');
    
       theDiv.hide();
    // make the div hidden by default.
    
       theDiv.prev('a').click(function(){ theDiv.toggle(); });
    // ^^^^^^^^^^^^^^^^^^^^^^             ^^^^^^^^^^^^^^^^
    // Attach the onclick                 hide & unhide.
    //  assume the <a> is 
    //  immediately before that <div>.
    // It may be better to give an
    //  id to that <a>.