我正在尝试创建具有4种手风琴样式的WordPress主题。我尝试玩弄我的代码以使其更短,但是我没有做任何技巧。有什么办法可以缩短时间?您的帮助将不胜感激!

jQuery(document).ready(function() {
    var allPanels = jQuery('.accordion-style1 > dd').hide();
    jQuery('.accordion-style1 > dt > a').click(function() {
        allPanels.slideUp();
        if(jQuery(this).parent().next().is(':hidden')) {
            jQuery(this).parent().next().slideDown();
        }
        return false;
    });
});

jQuery(document).ready(function() {
    var allPanels = jQuery('.accordion-style2 > dd').hide();
    jQuery('.accordion-style2 > dt > a').click(function() {
        allPanels.slideUp();
        if(jQuery(this).parent().next().is(':hidden')) {
            jQuery(this).parent().next().slideDown();
        }
        return false;
    });
});

jQuery(document).ready(function() {
    var allPanels = jQuery('.accordion-style3 > dd').hide();
    jQuery('.accordion-style3 > dt > a').click(function() {
        allPanels.slideUp();
        if(jQuery(this).parent().next().is(':hidden')) {
            jQuery(this).parent().next().slideDown();
        }
        return false;
    });
});

jQuery(document).ready(function() {
    var allPanels = jQuery('.accordion-style4 > dd').hide();
    jQuery('.accordion-style4 > dt > a').click(function() {
        allPanels.slideUp();
        if(jQuery(this).parent().next().is(':hidden')) {
            jQuery(this).parent().next().slideDown();
        }
        return false;
    });
});


http://jsfiddle.net/michellecantin/4mYdn/

最佳答案

应该这样做:

jQuery(document).ready(function () {
    jQuery('dl[class^=accordion-style] > dd').hide();
    jQuery('dl[class^=accordion-style] > dt > a').click(function () {
        jQuery(this).parent().parent().children("dd").slideUp();

        jQuery(this).parent().next("dd:hidden").slideDown();

        return false;
    });
});


参考:http://api.jquery.com/attribute-starts-with-selector/

演示:http://jsfiddle.net/4mYdn/7/

关于javascript - 如何缩短多种 Accordion 样式的JQuery脚本?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19755983/

10-10 22:01
查看更多