Switch/toggle div (jQuery)

后端 未结 9 661
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 09:39

I wish to accomplish a fairly simple task (I hope!)

I got two div tags and one anchor tags, like this:

forgot p         


        
9条回答
  •  生来不讨喜
    2020-12-01 10:29

    You could write a simple jQuery plugin to do this. The plugin would look like:

    (function($) {
        $.fn.expandcollapse = function() {
            return this.each(function() {
                obj = $(this);
                switch (obj.css("display")) {
                    case "block":
                        displayValue = "none";
                        break;
    
                    case "none":
                    default:
                        displayValue = "block";
                }
    
                obj.css("display", displayValue);
            });
        };
    } (jQuery));
    

    Then wire the plugin up to the click event for the anchor tag:

    $(document).ready(function() {
        $("#mylink").click(function() {
            $("div").expandcollapse();
        });
    });
    

    Providing that you set the initial 'display' attributes for each div to be 'block' and 'none' respectively, they should switch to being shown/hidden when the link is clicked.

提交回复
热议问题