我正在尝试用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;
});
});
答案 0 :(得分:2)
这应该做:
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;
});
});
答案 1 :(得分:2)
删除每个课程后的数字,例如<dl class="accordion-style">
var allPanels = jQuery('.accordion-style > dd').hide();
jQuery('.accordion-style > dt > a').on('click', function () {
jQuery(this).parents('.accordion-style').find('dd').slideUp();
if (jQuery(this).parent().next().is(':hidden'))
{
jQuery(this).parent().next().slideDown();
}
return false;
});
jsfiddle http://jsfiddle.net/code_snips/4mYdn/2/
如果您不想更改班级名称,可以做两件事
<dl class="accordion-style accordion-style1 ">
//在班级名称之前添加手风琴式
修改代码
var allPanels = jQuery('dl[class^=accordion-style] > dd').hide();
jQuery('dl[class^=accordion-style] > dt > a').on('click', function () {
jQuery(this).parents('dl[class^=accordion-style]').find('dd').slideUp();
if (jQuery(this).parent().next().is(':hidden')) {
jQuery(this).parent().next().slideDown();
}
return false;
});
答案 2 :(得分:1)
除了一个小差异外,所有功能是否相同?这将是函数参数的作用:)
function accordion(i) {
var allPanels = jQuery('.accordion-style'+i+' > dd').hide();
jQuery('.accordion-style'+i+' > dt > a').click(function() {
allPanels.slideUp();
if(jQuery(this).parent().next().is(':hidden')) {
jQuery(this).parent().next().slideDown();
}
return false;
});
}
jQuery(document).ready(function(){
for(var i=1;i<=4;i++)accordion(i);
});