问题
Possible Duplicate:
jQuery Toggle with Cookie
Am having a simple toggle, but the toggle always resets when the page refreshes, so I want to preserve its state by setting a cookie but am not having much Idea how should I do it...
Any idea how do I preserve the state of toggle?
http://jsfiddle.net/Qyufx/
<div class="question_trigger">
<p>Hi</p>
</div>
<div class="toggle_container">
<div class="block">Hello</div>
</div>
jQuery(document).ready(function(){
jQuery(".toggle_container").hide();
jQuery("div.question_trigger").click(function(){
jQuery(this).toggleClass("active").next().toggle("slow");
});
});
回答1:
Solution using cookie:
jQuery(document).ready(function() {
jQuery(".toggle_container").toggle($.cookie('showTop') != 'collapsed');
jQuery("div.question_trigger").click(function() {
jQuery(this).toggleClass("active").next().toggle();
var new_value = $(".toggle_container").is(":visible") ? 'expanded' : 'collapsed';
$.cookie('showTop', new_value);
});
});
FIDDLE
回答2:
Basic solution using PHP session variable to store the toggle state
Step 1 : Set the container visible or not durring page loading by checking the PHP session variable value :
jQuery(document).ready(function(){
if(<?php echo (isset($_SESSION['userId']['toggleState'] && $_SESSION['userId']['toggleState'] === FALSE) ? 'true' : 'false'; ?>)
$('.toggle_container').hide();
});
Step 2 : Add the script to update the PHP session variable
jQuery(document).ready(function(){
jQuery(".toggle_container").hide();
jQuery("div.question_trigger").click(function(){
jQuery(this).toggleClass("active").next().toggle("slow");
var data = ($(this).is(":visible")) ? 'true' : 'false';
$.ajax({
url: 'ajax/update.php',
method : 'post',
data : {data : data},
success: function(data) {
console.log('data updated');
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
});
Step 3 : implement ajax/update.php code (use the real userId database value)
<?php
$_SESSION['userId']['toggleState'] = (isset($_POST['data']) && $_POST['data'] === 'true') ? true : false;
?>
来源:https://stackoverflow.com/questions/14109903/preserve-toggle-state-using-jquery