刷新页面时 select、raido值保持不变

本文介绍了一种利用Cookies保存网页表单中select下拉菜单和radio按钮选择状态的方法,确保页面刷新后这些状态能够被记住。通过JavaScript操作Cookies来记录用户的选择,并在页面加载时恢复这些设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

刷新页面时,要使下拉菜单(select)、raido保持不变,用ajax是无法实现的。我想只能通过cookies才能实现。刷新前先把select或radio的值保存在cookies中,刷新后再填回去。下面是测试代码:


  1. <select name="sex" id="sex" onchange="save()">  
  2.     <option  value="01" selected ></opton>  
  3.     <option  value="02" ></opton>  
  4. </select>  
  5.   
  6. <input id="s1" type="radio" name="xueli" value="0" onclick="save()"/>本科  
  7. <input id="s2" type="radio" name="xueli" value="1" checked onclick="save()"/>专科  

  1. <script language="javascript" type="text/javascript">  
  2.     function save() {  
  3.         selectIndex = document.getElementById("sex").selectedIndex;  
  4.         document.cookie = 'selectIndex =' + selectIndex;  
  5.         radios = document.getElementsByName("xueli");  
  6.         for (i = 0; i < radios.length; i++) {  
  7.             if (radios[i].checked) document.cookie = 'radioindex =' + i;  
  8.         }  
  9.     }  
  10.     window.onload = function () {  
  11.         var cooki = document.cookie;  
  12.         if (cooki != "") {  
  13.             cooki = "{\"" + cooki + "\"}";  
  14.             cooki = cooki.replace(/\s*/g, "").replace(/=/g, '":"').replace(/;/g, '","');  
  15.             var json = eval("(" + cooki + ")"); //将coolies转成json对象  
  16.             document.getElementById("sex").options[json.selectIndex].selected = true;  
  17.             document.getElementsByName("xueli")[json.radioindex].checked = true;  
  18.         }  
  19.         else  
  20.             save();  
  21.     }  
  22. </script>  


下面这种方法更完美,适用于ASP JSP

<script type= "text/javascript" >
     function setCookie(name, value) {
         var exp =  new  Date();
         exp.setTime(exp.getTime() +  24  60  60  1000 );
         document.cookie = name +  "="  + escape(value) +  ";expires="  + exp.toGMTString();
     }
     function getCookie(name)
     {
         var regExp =  new  RegExp( "(^| )"  + name +  "=([^;]*)(;|$)" );
         var arr = document.cookie.match(regExp);
         if  (arr ==  null ) {
             return  null ;
         }
         return  unescape(arr[ 2 ]);
     }
</script>
<select id= "select_1"  onclick= "setCookie('select_1',this.selectedIndex)" >
     <option value= "apple" >apple</option>
     <option value= "banana" >banana</option>
     <option value= "cake" >cake</option>
</select>
<script type= "text/javascript" >
     var selectedIndex = getCookie( "select_1" );
     if (selectedIndex !=  null ) {
         document.getElementById( "select_1" ).selectedIndex = selectedIndex;
     }
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值