【问题标题】:jQuery cookies setting select drop down value after page refresh页面刷新后jQuery cookie设置选择下拉值
【发布时间】:2010-03-01 20:07:01
【问题描述】:

老实说,今天走到这一步后,我的大脑有点炸了。

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

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 示例:

<td>
<select id="titleDepend1" class="inlineSpace jTitle">
    <option value="Please select">Please select...</option>
    <option value="Mr">Mr</option>
    <option value="Mrs">Mrs</option>
    <option value="Ms">Ms</option>
    <option value="Miss">Miss</option>
    <option value="Dr">Dr</option>
    <option value="Other">Other</option>
</select>
<label for="otherDepend1" class="inlineSpace jOther">Other</label>
<input type="text" class="text jOther" name="otherDepend1" id="otherDepend1" maxlength="6" />

因此,如果这是用户第一次进入页面并且他们没有点击任何下拉菜单,那么第一个值将为空,而不是“请选择”。

【问题讨论】:

    标签: javascript jquery jquery-plugins


    【解决方案1】:

    我会更改这部分,如果 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(浏览器默认)将保持不变。

    【讨论】:

    • 干杯。当我试图检查一个 .length 的 cookie 是否存在时,我感到相当愚蠢,因为它一直返回 null。
    猜你喜欢
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多