jQuery .toggle() not working as expected with second function?

一个人想着一个人 提交于 2019-12-11 17:51:53

问题


I'm trying to create a button to show / hide a div below it, all is working fine, I'm just struggling with the last bit!

I need to distinguish wether it's a show or hide action so I can pass the variable elsewhere, here's what I have..

$(this).find('.hide-close').click(
            function() {
                $(this).siblings('.dragbox-content').toggle(function() { 

                    alert($(this).parent().attr("id") + ' Show');

                    },function() { 

                    alert($(this).parent().attr("id") + ' Hide');

                    }

                );

            })
        .end()
        });

If use the following code, taking out the second function within toggle(), it works?! But then I don't have a show / hide variable.

$(this).find('.hide-close').click(
            function() {
                $(this).siblings('.dragbox-content').toggle(function() { 

                    alert($(this).parent().attr("id") + ' Show');

                    }

                );

            })
        .end()
        });

Thanks in advance for any help, hopefully it's something really simple I just can't see! :)


回答1:


You can use $(this).is(":visible") inside the function to check whether its visible or not.




回答2:


The jQuery toggle function is for assigning functions to execute when an event(mouse click) occurs. To actually fire an event, you will have to call the click function.

$('.dragbox-content').toggle(function() { 
        alert($(this).parent().attr("id") + ' Show');
    },function() { 
        alert($(this).parent().attr("id") + ' Hide');
    }
);

Use this piece of code to assign the function to be executed on click.

$(this).find('.hide-close').click(
function() {
    $(this).siblings('.dragbox-content').click();
})
.end();

and this to fire the event.



来源:https://stackoverflow.com/questions/3036405/jquery-toggle-not-working-as-expected-with-second-function

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