问题
Can anyone help me with this, I can't find a script on the internet that does this in jQuery. I need to remember the last state of drop down menu so that on page load the drop down option is already selected. The cookie expiration date should be 90 days or let me specify in the script. Since I already use jQuery on my page I want this cookie script to use jquery, jquery cookie plugin. Thank you in advance. I'm not a programmer, but I try.
<body onLoad="GETcookie()">
<select onChange="SETcookie()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
回答1:
With the plugin that I've included, you can get and set cookies.
Your code would look a little something like this:
//checks if the cookie has been set
if($.cookie('remember_select') != null) {
// set the option to selected that corresponds to what the cookie is set to
$('.select_class option[value="' + $.cookie('remember_select') + '"]').attr('selected', 'selected');
}
// when a new option is selected this is triggered
$('.select_class').change(function() {
// new cookie is set when the option is changed
$.cookie('remember_select', $('.select_class option:selected').val(), { expires: 90, path: '/'});
});
Here is what you select would look like:
<select class="select_class">
<option value="1">Row 1</option>
<option value="2">Row 2</option>
<option value="3">Row 3</option>
</select>
Here's a demo of it on jsFiddle: http://jsfiddle.net/RastaLulz/3HxCF/3/
Here's the jQuery cookie plugin incase you don't already have it: http://pastebin.com/CBueT8LP
回答2:
First don't do body onLoad (should be onload in lowercase), but in my example you don't need your onload and onchange but :
// This replace onload
$(function() {
// Read your cookie and other things up to you to do...
$.cookie('the_cookie');
// on change of your select
$('select').on('change', function() {
// Set the cookie
$.cookie('the_cookie', 'the_value', { expires: 90, path: '/'});
});
});
PS: my script is jQuery 1.7 (for the on) so look if you are up to date !
Edit: Set the 90 days expires
来源:https://stackoverflow.com/questions/8483951/jquery-cookie-to-remember-last-state-of-drop-down-menu