代码之家  ›  专栏  ›  技术社区  ›  leora Matt Lacey

在同一区域切换两个div的最佳方式是什么

  •  9
  • leora Matt Lacey  · 技术社区  · 15 年前

    我有divB display style=none。

    然后我想把链接改成“Show viewA”

    在jquery中,最优雅的方法是什么?

    7 回复  |  直到 15 年前
        1
  •  10
  •   PeterWong    15 年前

    通过使用 toggle()

    $("#link").toggle(function() {
      toggleDivs();
      $(this).html("Show viewA");
    }, function() {
      toggleDivs();
      $(this).html("Show viewB");
    });
    
    function toggleDivs() {
      $("#divA, #divB").toggle();
    }
    
        2
  •  4
  •   user113716    15 年前

    很简单。

    例子: http://jsfiddle.net/Zmsnd/

    $('#toggle').click(function() {
        $('#container > .toggleMe').toggle();
        $(this).text(function(i,txt) { return txt === "Show viewB" ? "Show viewA" : "Show viewB"; });
    });
    
        3
  •  3
  •   PeterWong    15 年前

    $("#link").click(function(e) {
      e.preventDefault();
      $("#divA, #divB").toggle();
      $(this).text(function(i, text) { return (text == "Show viewA") ? "Show viewB" : "Show viewA" });
    });
    
        4
  •  1
  •   Harmen    15 年前

    不难,试试这样的:

    var $divA = $('#a'),
        $divB = $('#b'),
        $link = $('#link');
    
    // Initialize everything
    $link.text( 'Show A' );
    $divA.hide();
    
    $link.click(function(){
    
      // If A is visible when the link is clicked
      // you need to hide A and show B
      if( $divA.is( ':visible' ) ){
        $link.text( 'Show A' );
        $divA.hide();
        $divB.show();
      } else {
        $link.text( 'Show B' );
        $divA.show();
        $divB.hide();
      }
    
      return false;
    });
    

    Example on jsFiddle

        5
  •  0
  •   John    15 年前

    replaceWith 方法(即。, target.replaceWith(newContent) ). 顾名思义,它将取代 target newContent . 最好的部分是它会在适当的地方做。

    divA.replaceWith(divB);
    ...
    divB.replaceWith(divA);
    
        6
  •  0
  •   George    15 年前
    var divA = $("#divA");
    var divB = $("#divB");
    var originalState = true;
    
    $("#toggler").click(function(e) {
        originalState = !originalState;
        if (originalState) {
            divB.hide();
            divA.show();
        } else {
            divA.hide();
            divB.show();
        }
        $(this).html(originalState ? "Show viewB" : "Show viewA");
        e.preventDefault(); // Assuming you're using an anchor and "#" for the href
    });
    
        7
  •  0
  •   Valentin Flachsel    15 年前

    $("#link").click(function() {
        $("div[id^=tog_]").toggle();
        $(this).text("Show " + $("div[id^=tog_]").not(":visible").attr("id").substr(4));
    });
    

    穿上它 JSFiddle .