jQuery text() change on toggle()?

2019-03-31 18:53发布

I want to make a script that is changing toggle link text depending on others element visibility.

So while #form is visible I want the #form-container a text to be "Hide...", and while it's hidden I want the text to be "Show...".

I've tried this line - if($('#form').is(":visible")){ another way: if($('#form').is(":visible") == "true"){ - but it also doesn't work.

What's wrong? How to change text every time another item is toggled?

$('.toggle').click(
    function()
    {
        $('#form').slideToggle();

            if($('#form').is(":visible")){
                $('#form-container a').text("Hide form container");
            }
            else {
                $('#form-container a').text("Show form container");  
            } 
    });

Thanks.

2条回答
smile是对你的礼貌
2楼-- · 2019-03-31 19:03

You can use toggle on the form element.

$("#form").slideToggle(
  function () {
    //Hide
  },
  function () {
    //Show
  }
);

source: http://api.jquery.com/toggle/

查看更多
Lonely孤独者°
3楼-- · 2019-03-31 19:09

It'll always be visible while animating, you can check the visibility in the .slideToggle() callback so it checks when it finishes animating, like this:

$('.toggle').click(function() {
  $('#form').slideToggle(function() {
    $('#form-container a').text(
      $(this).is(':visible') ? "Hide form container" : "Show form container"
    );
  });
});
查看更多
登录 后发表回答