javascript jQuery text() 在 toggle() 上发生变化吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3471973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:16:48  来源:igfitidea点击:

jQuery text() change on toggle()?

javascriptjquerytoggle

提问by bat

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...".

因此,虽然#form 可见,但我希望 #form-container 的文本为“隐藏...”,而在隐藏时,我希望文本为“显示...”。

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

我试过这一行 - if($('#form').is(":visible")){ 另一种方式: if($('#form').is(":visible") == "true "){ - 但它也不起作用。

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.

谢谢。

回答by Nick Craver

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

动画时它始终可见,您可以在.slideToggle()回调中检查可见性,以便它在完成动画时检查,如下所示:

$('.toggle').click(function() {
  $('#form').slideToggle(function() {
    $('#form-container a').text(
      $(this).is(':visible') ? "Hide form container" : "Show form container"
    );
  });
});

回答by Nacho

You can use toggle on the form element.

您可以在表单元素上使用切换。

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

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

来源:http: //api.jquery.com/toggle/