1

我正在尝试使用选择框选项的值设置 cookie。我正在使用位于以下位置的 jquery.cookie.js 插件:https ://github.com/carhartl/jquery-cookie

<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#set_state").change(function() {
        var theState = $(this).val();
        $.cookie('set_state', theState, { expires: 5, path: '/' });
    });
});
</script>
</head>
<body>
<select id="set_state" name="state">
    <option value="" selected="selected"></option>
    <option value="">None</option>
    <option value="AL">AL</option>
    <option value="AK">AK</option>
    <option value="AZ">AZ</option>
    <option value="AR">AR</option>
    <option value="CA">CA</option>
    <option value="CO">CO</option>
    <option value="CT">CT</option>
    <!-- no need to post them all here -->
</select>
</body>

如果我使用警告框来显示变量theState,它可以工作,但我无法让$.cookie函数工作......我做错了什么?

4

1 回答 1

0

这是使用 jQuery cookie 插件设置 cookie 的完整示例。

HTML:

<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript' src='http://codebins.com/userUploads/3/jquery.cookie.js'></script>
</head>
<body>
     <select id="set_state" name="state">
        <option value="" selected="selected"></option>
        <option value="">None</option>
        <option value="AL">AL</option>
        <option value="AK">AK</option>
        <option value="AZ">AZ</option>
        <option value="AR">AR</option>
        <option value="CA">CA</option>
        <option value="CO">CO</option>
        <option value="CT">CT</option>
        <!-- no need to post them all here -->
    </select>
    <input type="button" id="btncookie" value="get cookie" />
    <input type="button" id="btndelcookie" value="delete cookie" />
</body>

查询:

$(document).ready(function() {
   $("#set_state").change(function() {
       var theState = $(this).val();
       $.cookie('set_state', theState, {
           expires: 5,
           path: '/'
       });
  });
  $("#btncookie").click(function() {
      alert("Your Selected Value from Cookie is : " + $.cookie('set_state'));
  });
  $("#btndelcookie").click(function() {
       $.cookie('set_state', '', {
        expires: -1
       });
       $("#set_state").val("");
       alert('Cookie is deleted now, try to get cookie..!');
   });
});

在代码箱上尝试上面的示例: http ://codebins.com/codes/home/4ldqpc6

于 2012-07-02T15:31:13.203 回答