简化这些jquery?

时间:2011-01-21 04:12:54

标签: jquery

我如何简化这些jquery代码?任何的想法?

   $('#expand').click(function() {
            $('.bbit-tree-elbow-plus').addClass('bbit-tree-elbow-minus');
            $('.bbit-tree-elbow-minus').removeClass('bbit-tree-elbow-plus');
            $('ul.bbit-tree-node-ct .bbit-tree-elbow-end-plus').addClass('bbit-tree-elbow-end-minus');
            $('ul.bbit-tree-node-ct .bbit-tree-elbow-end-minus').removeClass('bbit-tree-elbow-end-plus')
            if ($("#preview_root").hasClass("bbit-tree-node-collapsed")) {
                $('#preview_root').removeClass('bbit-tree-node-collapsed');
                $('#preview_root').addClass('bbit-tree-node-expanded');
                $('ul.bbit-tree-root .bbit-tree-elbow-end-plus').addClass('bbit-tree-elbow-end-minus');
                $('ul.bbit-tree-root .bbit-tree-elbow-end-minus').removeClass('bbit-tree-elbow-end-plus')
                $('.bbit-tree-node-ct').show();
            }
            $(".bbit-tree-node-ct ul").show();
        });
        $('#collapse').click(function() {
            $('.bbit-tree-elbow-minus').addClass('bbit-tree-elbow-plus');
            $('.bbit-tree-elbow-plus').removeClass('bbit-tree-elbow-minus');
            $('ul.bbit-tree-node-ct .bbit-tree-elbow-end-minus').addClass('bbit-tree-elbow-end-plus');
            $('ul.bbit-tree-node-ct .bbit-tree-elbow-end-plus').removeClass('bbit-tree-elbow-end-minus')
            $(".bbit-tree-node-ct ul").hide('slow');
        });

2 个答案:

答案 0 :(得分:2)

您可以使用.toggleClass代替addClass removeClass,并将您的类名作为函数的参数。

Toggle Class

答案 1 :(得分:1)

是的,使用toggleClass作为TALLBOY提到。另外,考虑将$('。class')调用放入变量中。例如:

var plus = $('.bbit-tree-elbow-plus');

从此开始,使用它像:

plus.toggleClass('bbit-tree-elbow-minus');