jQuery toggle and IF visible

最后都变了- 提交于 2020-03-17 10:28:11

问题


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

$("#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.

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


回答1:


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.

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

function callbackFn(){

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

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


}



回答2:


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.');
    }
}); 



回答3:


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 »");
});


来源:https://stackoverflow.com/questions/1193405/jquery-toggle-and-if-visible

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!