jQuery 切换和 IF 可见

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1193405/
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-08-26 10:53:03  来源:igfitidea点击:

jQuery toggle and IF visible

jquerytoggle

提问by j82374823749

I have a div which contains settings and options on an account management page.

我有一个 div,其中包含帐户管理页面上的设置和选项。

$("#moreOptions").slideToggle('slow');
if ($("#moreOptions").is(":visible") == true) {
    $("#lnkMoreOpt").text("Less Options ?")
}
else {
    $("#lnkMoreOpt").text("More Options ?")
}

The code above should change the text of the more/less options link depending on whether it is visible or not, however it appears jQuery does not treat toggling as making it invisible/visible.

上面的代码应该根据它是否可见来更改更多/更少选项链接的文本,但是看起来 jQuery 不会将切换视为使其不可见/可见。

How can I implement this while still using the toggle function?

如何在仍然使用切换功能的同时实现这一点?

回答by redsquare

You need to use the callback function. By the time the if statement is evaluated the slideToggle will not have completed and you will get incorrect results.

您需要使用回调函数。到 if 语句被评估时,slideToggle 还没有完成,你会得到不正确的结果。

$("#moreOptions").slideToggle('slow', callbackFn);

function callbackFn(){

     var $link = $("#lnkMoreOpt");

     $(this).is(":visible") ? $link.text("Less Options ?") : $link.text("More Options ?");


}

回答by basim

I think this code will work

我认为这段代码会起作用

$('#element').toggle('slow', function() {
    if($(this).is(':hidden')) { 
        $(this).text('This element is hidden.');
    }
    else {
        $(this).text('This element is visible.');
    }
}); 

回答by Ludovit Scholtz

I prefer not to use separate functions because when one function does not need to be used twice, it is waste of code.. i believe this is easier to understand when someone comes to it..

我不喜欢使用单独的函数,因为当一个函数不需要使用两次时,这是浪费代码..我相信当有人谈到它时,这更容易理解..

$("#moreOptions").slideToggle('slow', function(){
     var $link = $("#lnkMoreOpt");
     $(this).is(":visible") ? $link.text("Less Options ?") : $link.text("More Options ?");
});