javascript-jQuery cookie设置在页面刷新后选择下拉值

前端之家收集整理的这篇文章主要介绍了javascript-jQuery cookie设置在页面刷新后选择下拉值 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

老实说,今天我走了这么远后,我的脑子反而被炸了.

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

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

我正在使用此jQuery根据其ID为不同的标题下拉列表设置Cookie:

  1. $(document).ready(function() {
  2. // hide 'Other' inputs to start
  3. $('.jOther').hide();
  4. // event listener on all select drop downs with class of jTitle
  5. $(".jTitle").change(function(){
  6. //set the select value
  7. var val = $(this).val();
  8. if(val != "Other") {
  9. //$(this).nextAll('.jOther').hide();
  10. $(this).parent().find(".jOther").hide();
  11. } else {
  12. //$(this).nextAll('.jOther').show();
  13. $(this).parent().find(".jOther").show();
  14. }
  15. // Sets a cookie with named after the title field's ID attribute
  16. $(this).cookify();
  17. });
  18. $(".jTitle").each(function(){
  19. // get the id of each Title select drop down
  20. var $titleId = $(this).attr('id');
  21. // get the value of the cookie for each cookie created above in $(this).cookify()
  22. var $cookieValue = $.cookies.get($titleId);
  23. // if value is 'Other' make sure it is shown on page refresh
  24. if ($cookieValue == 'Other') {
  25. // Show the other input
  26. $(this).parent().find(".jOther").show();
  27. // set select value to 'Other'
  28. $(this).val('Other');
  29. } else {
  30. // set to whatever is in the cookie
  31. $(this).val($cookieValue);
  32. }
  33. });

});

发生的情况是,当我未设置Cookie时,如果希望将其默认设置为“请选择”,则选择下拉列表将显示空白选项.

我正在使用的示例HTML:

  1. <td>
  2. <select id="titleDepend1" class="inlineSpace jTitle">
  3. <option value="Please select">Please select...</option>
  4. <option value="Mr">Mr</option>
  5. <option value="Mrs">Mrs</option>
  6. <option value="Ms">Ms</option>
  7. <option value="Miss">Miss</option>
  8. <option value="Dr">Dr</option>
  9. <option value="Other">Other</option>
  10. </select>
  11. <label for="otherDepend1" class="inlineSpace jOther">Other</label>
  12. <input type="text" class="text jOther" name="otherDepend1" id="otherDepend1" maxlength="6" />

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

最佳答案
我将更改此部分,如果cookie不存在,请不要与下拉菜单混淆:

  1. $(".jTitle").each(function(){
  2. var $titleId = $(this).attr('id');
  3. var $cookieValue = $.cookies.get($titleId);
  4. if ($cookieValue == 'Other') {
  5. $(this).parent().find(".jOther").show();
  6. $(this).val('Other');
  7. } else if($cookieValue) {
  8. $(this).val($cookieValue);
  9. }
  10. });

唯一的变化是在最后添加一个if检查,看是否有一个cookie …如果不是下拉列表中默认位置0(浏览器默认),则将不予处理.

@H_404_41@

猜你在找的jQuery相关文章