我在同一页上有2支手风琴。
首先,我有一个页面,Freemarker,其中包括另外两个有手风琴的Freemarkers。
[#include "page1.ftl"]
[#include "page2.ftl"]
第1页:
<h3 class="trigger"><div id="toggle-image"> Page1</div></h3>
<div class="toggle-container">
第2页:
<h3 class="trigger2"><div id="toggle-image2"> Page2</div></h3>
<div class="toggle-container2">
Java脚本文件上的:
$(document).ready(function(){
$('#toggle-image').attr("class", "toggle-image-expand");
//Hide (Collapse) the toggle containers on load
$(".toggle-container").hide();
$("h3.trigger").click(function(){
$(this).toggleClass("active").next().slideToggle("slow");
if($('#toggle-image').attr("class") == "toggle-image-collapse") {
$('#toggle-image').attr("class", "toggle-image-expand");
} else {
$('#toggle-image').attr("class", "toggle-image-collapse");
}
return false;
});
});
$(document).ready(function(){
$('#toggle-image2').attr("class", "toggle-image-expand");
//Hide (Collapse) the toggle containers on load
$(".toggle-container2").hide();
$("h3.trigger2").click(function(){
$(this).toggleClass("active").next().slideToggle("slow");
if($('#toggle-image2').attr("class") == "toggle-image-collapse") {
$('#toggle-image2').attr("class", "toggle-image-expand");
} else {
$('#toggle-image2').attr("class", "toggle-image-collapse");
}
return false;
});
它工作正常,但我在js上使用的冗余代码是典型的,不同之处在于它使用的变量。 我怎么能让它动态!! });
答案 0 :(得分:0)
这是您正在寻找的基本想法:
$(document).ready(function(){
var toggler = $('div[id*="toggle-image"]');
toggler.attr("class", "toggle-image-expand");
//Hide (Collapse) the toggle containers on load
$("div[class*='toggle-container']").hide();
$("h3[class*='trigger']").click(function(){
var toggler_inner = $(this).find(toggler);
$(this).toggleClass("active").next().slideToggle("slow");
if (toggler_inner.attr("class") == "toggle-image-collapse") {
toggler_inner.attr("class", "toggle-image-expand");
}
else {
toggler_inner.attr("class", "toggle-image-collapse");
}
return false;
});
});
答案 1 :(得分:0)
page1(添加了一个容器div,“toggle-image”类名称):
<div>
<h3 class="trigger">
<div id="toggle-image" class="toggle-image">
Page1
</div>
</h3>
<div class="toggle-container">
</div>
</div>
第2页(相同的更改):
<div>
<h3 class="trigger">
<div id="toggle-image2" class="toggle-image">
Page2
</div>
</h3>
<div class="toggle-container">
</div>
</div>
JavaScript(使用类选择器,兄弟选择器,改进的类逻辑):
$(document).ready(function(){
$('.toggle-image').attr("class", "toggle-image-expand");
//Hide (Collapse) the toggle containers on load
$(".toggle-container").hide();
$("h3.trigger").click(function(){
$(this).toggleClass("active").next().slideToggle("slow");
$(this).children('.toggle-image')
.toggleClass('toggle-image-collapse')
.toggleClass('toggle-image-expand');
return false;
});
});