简体   繁体   中英

Second handler cannot run inside toggle-event

i try to create simple show/hide box using toggle but when box is open the button will change to "-" and when box closed, button will change back to "+"

you can check my jsfiddle here

i try with this code using first and second handler

$(document).ready(function () {
    //default
    $('.content').hide();

    $('#b_1').click(function () {

        $('.content').toggle(function () {
            $('#b_1').prop('value', '-');    //first handler
        },
            function() {
            $('#b_1').prop('value', '+');    //second handler
        });

    });
});

but second handler not working ..

I have seen people using second handler in toggle .. but of what I know there is no second handler in toggle function.. check the docs ..(let me know if I am wrong).. if its the toggle-event then it is deprecated in jQuery 1.8 and removed in jQuery 1.9.

Anyway here is how I would do to solve your problem

$('#b_1').click(function () {

 $('.content').toggle('slow',function () {
     if($('.content').is(':visible')){
        $('#b_1').attr('value', '-');
     }else{
        $('#b_1').attr('value', '+');
     }
 });
 });  

working fiddle here

Try

<script type="text/javascript">

    $(function()
    {
        $('.content').hide();

        $('#b_1').toggle(function ()
        {
            $(this).attr('value', '-');
            $(this).next('.content').show();
        },
        function()
        {
            $(this).attr('value', '+');
            $(this).next('.content').hide();
        });

    });

</script>

Better handle your toggle() manually.

$('#b_1').click(function () {

    var $button = $(this);
    $('.content').toggle(function () {
        var symbol = $button.attr("value"),
            newSymbol = symbol == "+" ? "-" : "+";

        $button.attr("value", newSymbol);
    });

});

JSFiddle .

You can try this: fiddle

$(document).ready(function () {
    var i = 0;
    $('.content').hide();
    $('#b_1').click(function () {
        if (i == 0) {
            $('.content').toggle('slow', function () {
                $('#b_1').val('-');
                i = 1;
            });
        } else if (i = 1) {
            $('.content').toggle('slow', function () {
                $('#b_1').val('+');
                i = 0;
            });
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM