【发布时间】:2014-08-16 07:01:12
【问题描述】:
我在 Nicolas R 的帮助下想出了一个 JQuery 切换,它使用 cookie 保存切换的状态,但目前在实现它时遇到了麻烦,因为一旦激活它就会为所有按钮拉入相同的标题.
请在下面找到:
HTML:
<div>
<a href="#" id="slide1">Slide Toggle +</a>
<div id="slide1panel" style="display:none; background-color:#4CF;width:100px;height:200px;"></div>
</div>
<div>
<a href="#" id="slide2">Slide Toggle +</a>
<div id="slide2panel" style="display:none; background-color:#4CF;width:100px;height:200px;"></div>
</div>
jQuery
$(document).ready(function() {
// check the cookies when the page loads
// 1st panel
if ($.cookie('currentToggleslide1panel') === 'visible') {
togglePanel($('#slide1panel'), $('#slide1'), true, 0);
}
// 2nd panel
if ($.cookie('currentToggleslide2panel') === 'visible') {
togglePanel($('#slide2panel'), $('#slide2'), true, 0);
}
//handle the clicking of the show/hide toggle button of the 1st panel
$('#slide1').click(function() {
//toggle the panel as required, base on current state
if ($('#slide1').text() === "Slide Toggle +") {
togglePanel($('#slide1panel'), $('#slide1'), true, 'slow');
}
else {
togglePanel($('#slide1panel'), $('#slide1'), false, 'slow');
}
});
//handle the clicking of the show/hide toggle button of the 2nd panel
$('#slide2').click(function() {
//toggle the panel as required, base on current state
if ($('#slide2').text() === "Slide Toggle +") {
togglePanel($('#slide2panel'), $('#slide2'), true, 'slow');
}
else {
togglePanel($('#slide2panel'), $('#slide2'), false, 'slow');
}
});
});
function togglePanel(panel, button, show, toggleSpeed) {
if(toggleSpeed > 0 || toggleSpeed === 'slow' || toggleSpeed === 'fast') {
panel.slideToggle(toggleSpeed);
} else {
panel.toggle();
}
if (show) {
// Set a cookie containing the panel name
$.cookie('currentToggle' + panel.attr('id'), 'visible', { path: '/' });
button.text('Slide Toggle -');
} else {
// Set a cookie containing the panel name
$.cookie('currentToggle' + panel.attr('id'), 'hidden', { path: '/' });
button.text('Slide Toggle +');
}
}
谢谢!
【问题讨论】:
标签: javascript jquery cookies