返回同一页面后显示下拉列表值相同

时间:2012-11-01 10:32:52

标签: jquery

您好我有一个select列表的页面,其中包含以下内容

<select class="othdebt" id="othdebt" name="othdebt">
    <option value="Cate" >Categorical</option>
    <option value="Cont">Continuous</option>
    <option value="Data">Date</option>
</select>

当我转到其他页面并返回select列表页面时,我希望看到相同的选项。

我使用以下jQuery来执行此操作。

<script type="text/javascript">
    $(".othdebt").each(function(){
        var $titleId = $(this).attr('id');
        var $cookieValue = $.cookies.get($titleId);
        if ($cookieValue) {
            $(this).val($cookieValue);
        }                       
    });
</script>

但它没有任何其他建议吗?

4 个答案:

答案 0 :(得分:0)

您错误地收到了id。试试这个:

var titleId = $(this).attr('id');

或者:

var titleId = this.id;

注意我还从变量名的开头删除了$。此约定保留给包含jQuery对象的变量 - 这不是。

答案 1 :(得分:0)

将所有代码保存在document.ready()

修改:设置Cookie

$(".othdebt").​change(function(){
    $.cookies('titleId',$(this).val());
});​

在加载页面时获取cookie

document.ready(function(){
$(".othdebt").each(function() {
    //var titleId = $(this).attr('id');
    var $cookieValue = $.cookies.get('titleId');
    if ($cookieValue) {
        $(this).val($cookieValue);
    }
});
});

答案 2 :(得分:0)

首先,使用此原生javascript函数设置cookie。

document.cookie = 'othdebt=Data';

然后用这个

获取cookie
var objId = $('.othdebt').attr('id');
var cookieValue = document.cookie.match( '(^|;) ?' + objId + '=([^;]*)(;|$)' );
 if ( cookieValue )
    cv = ( unescape ( cookieValue[2] ) );
else
    cv = null;

cv持有cookie值

 $(".othdebt option").each(function(){
  if (cv == $(this).val())
  {
    $('.othdebt').val(cv);
  }
});

我已经测试了这个,它对我有用;)

答案 3 :(得分:0)

最后我找到了自己的解决方案

这是 DEMO

/* Here's the actual code. */

if($.cookie('remember_select') != null) {

    $('.select_class option[value="' + $.cookie('remember_select') + '"]').attr('selected', 'selected');

}

$('.select_class').change(function() {

    $.cookie('remember_select', $('.select_class option:selected').val(), { expires: 90, path: '/'});

});​