Ric*_*nop 2 jquery toggle slide
我会尽量保持这个简短.我正在尝试创建用户单击展开按钮时隐藏或显示的文本框.我正在使用toggle()方法.
标记是这样的:
<span id="toggle0">+</span>
<div id="toggle0Container">
blablabla...
<div>
<span id="toggle1">+</span>
<div id="toggle1Container">
blablabla...
<div>
<span id="toggle2">+</span>
<div id="toggle2Container">
blablabla...
<div>
// etc
Run Code Online (Sandbox Code Playgroud)
#toto0应该切换#tockt0_tatainer,#toggle1切换#topggle1Container,依此类推.这都是由PHP生成的,因此可以有任意数量的这些容器.
这是JQuery代码:
$(document).ready(function() {
// array of numbers, it's pretty redundant, there will never be more than 30 containers
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9 , 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36];
// hide all containers first
jQuery.each(arr, function() {
$('#toggle' + this + 'Container').hide();
});
// now the toggle buttons
jQuery.each(arr, function() {
$('#toggle' + this).click(function() {
// this line is not working
$('#toggle' + this + 'Container').slideToggle('slow');
// and this just changes the toggle button from + to -
if ($(this).html() == '+') {
$(this).html('-');
} else {
$(this).html('+');
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
它的工作原理除了切换部分(我在不起作用的行上方添加了注释).哪里出了问题?
这是因为"this"现在处于不同的范围,并且指的是实际的#toggleN DOM元素,而不是数组中的一个数字.
我建议你抛弃数组,并使用不同的选择器,如:
$("div[id^=toggle][id$=container]").hide();
$("span[id^=toggle]").click(function() {
$(this).find("span[id^=toggle][id$=container]").slideToggle("slow");
// .. do your other html stuff
}
Run Code Online (Sandbox Code Playgroud)
只需抛弃每个人并用那些替换切换选择器.