jQuery cookies设置页面刷新后选择下拉值

老实说,今天到目前为止,我的大脑相当油炸。

我正在尝试使用此插件保存页面上多个选择下拉列表的状态:

http://plugins.jquery.com/project/cookies

我正在使用这个jQuery根据他们的ID设置不同标题下拉列表的cookie:

$(document).ready(function() { // hide 'Other' inputs to start $('.jOther').hide(); // event listener on all select drop downs with class of jTitle $(".jTitle").change(function(){ //set the select value var val = $(this).val(); if(val != "Other") { //$(this).nextAll('.jOther').hide(); $(this).parent().find(".jOther").hide(); } else { //$(this).nextAll('.jOther').show(); $(this).parent().find(".jOther").show(); } // Sets a cookie with named after the title field's ID attribute $(this).cookify(); }); $(".jTitle").each(function(){ // get the id of each Title select drop down var $titleId = $(this).attr('id'); // get the value of the cookie for each cookie created above in $(this).cookify() var $cookieValue = $.cookies.get($titleId); // if value is 'Other' make sure it is shown on page refresh if ($cookieValue == 'Other') { // Show the other input $(this).parent().find(".jOther").show(); // set select value to 'Other' $(this).val('Other'); } else { // set to whatever is in the cookie $(this).val($cookieValue); } }); 

});

发生的事情是,当没有设置cookie时,当我希望它默认为“请选择”时,选择下拉列表显示一个空白选项。

我正在使用的示例HTML:

   Please select... Mr Mrs Ms Miss Dr Other    

因此,如果这是用户第一次在页面上并且他们没有点击任何下拉列表,则第一个值将为空而不是“请选择”。

我会改变这一部分,如果cookie不在那里,就不要搞砸了下拉列表:

 $(".jTitle").each(function(){ var $titleId = $(this).attr('id'); var $cookieValue = $.cookies.get($titleId); if ($cookieValue == 'Other') { $(this).parent().find(".jOther").show(); $(this).val('Other'); } else if($cookieValue) { $(this).val($cookieValue); } }); 

唯一的变化是在结尾处添加if检查,看看是否有cookie …如果不是下拉列表中的默认位置0(浏览器默认值)将保持不变。