简体   繁体   English

使用jQuery切换显示/隐藏

[英]Toggle show/hidden with jquery

I need to use jquery to toggle two elements to show/hide. 我需要使用jquery来切换两个元素以显示/隐藏。 I want the button to say "hide text" and change to "show text" when it is clicked and of course I want the text to toggle from show to hide as the button is clicked. 我希望按钮在单击时说“隐藏文本”并更改为“显示文本”,当然,我希望在单击按钮时将文本从显示切换为隐藏。 I have this to change it one time but I do not know how to change it back or make it toggle. 我有一次更改它,但我不知道如何将其更改回或使其切换。

$(function() {
    $('button#1').click(function() {
        $('#one').fadeOut();
    });

    $('button#1').click(function() {
        $('button#1').html('Show Text');
    });
});

http://jsfiddle.net/fwdzm/1/ http://jsfiddle.net/fwdzm/1/

Use the toggle callbacks ! 使用切换回调!

$(function() {
    var $btn1 = $('button#1').click(function() {
        $('#one').toggle('slow', function () {
            if ($(this).is(':visible')) {
                $btn1.html('Hide Text');
            } else {
                $btn1.html('Show Text');
            }
        });
    });
});
$('button#1').click(function() {
    var $btn = $(this);
    $('#one').toggle('slow', function() {
       if ($(this).is(':visible')) {
          $btn.text('Hide');
       } else {
          $btn.text('Show Text');
       }
    });
});

Try something like this 试试这个

$(function() {
  $('button#1').click(function(){
    if ($('#one').is(':visible')) {
      $('#one').fadeOut();
      $(this).html('Show Text');
    } else {
      $('#one').fadeIn();
      $(this).html('Hide Text');
    }
  });
});

Save the current state in a variable and then based on that variable you either show or hide your elements and change the text on the button. 将当前状态保存到变量中,然后根据该变量显示或隐藏元素并更改按钮上的文本。

HTML 的HTML

<button id="toggleBtn" type="button">Hide Text</button>
<span id="element">Your text is here</span>

JAVASCRIPT JAVASCRIPT

var status = "shown";

function toggleElement() {
    if (status == "shown") {
        $('#element').hide();
        $("#toggleBtn").html('Show Text');
        status = "hidden";
    } else {
        $('#element').show();
        $("#toggleBtn").html('Hide Text');
        status = "shown";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM