如何用js操纵cookie

时间:2016-07-28 06:17:50

标签: javascript session cookies session-cookies

此处此代码只存储te选项,并且它会从adio按钮生成结果。我想要它使用文本框或输入字段的单选按钮。那应该改变什么?

<script language="JavaScript">
var timer,timecounter=0
function readCookie(name)
{
   var result=null;
   var myCookie=document.cookie+";";
   var searchName=name+"=";
   var start=myCookie.indexOf(searchName);
   var end;
   if(start!=-1)
    {
      start+=searchName.length;
      end=myCookie.indexOf(";",start);
      result=myCookie.substring(start,end);
    }
  return result;      
}
function writeCookie(name)
{
  var expDate=new Date();
  var day=1*24*60*60;
  expDate.setTime(expDate.getTime()+day);
  document.cookie=name+"="+timecounter;
}
function starttimer(counter,ans)
{
var cook 
    timecounter=parseInt(readCookie(<%=chr(34) & examname&"totaltime"& chr(34)%> ))
   var index=-1
   if(ans=="A")
        index=0
   else if(ans=="B")
        index=1      
   else if(ans=="C")
        index=2      
   else if(ans=="D")
        index=3

   if(document.examform.qno.value-1<=counter&&index!=-1)
        document.examform.elements[index].checked=true
      timer=setInterval("change()",1000)

}
function stoptimer()
{
    writeCookie("<%=examname&"totaltime"%>");  
    clearInterval(timer)
}
function change()
{
    var hrs,mins,secs;
    hrs=parseInt(timecounter/3600);
    mins=parseInt(timecounter/60);
    secs=timecounter%60;
    window.status="Time Remaining : "+hrs+":"+mins+":"+secs;
    rem_time.innerText="Time Remaining :"+hrs+":"+mins+":"+secs;
    timecounter--
    if(timecounter==-1)
      {
        store_ans()
        stoptimer()
        document.examform.submit()    

      }           
}
function store_ans()
{
     var elems=document.examform.elements 
     var ans=""
    for(var i=0;i<elems.length;i++)
     if((elems[i].type=="radio"||elems[i].type=="checkbox")&&elems[i].checked)
         ans=ans+elems[i].value    
    document.examform.answer.value=ans
    if(ans=="")
      document.examform.answer.value="Not Attempted"    
    stoptimer()
}       
</script>

1 个答案:

答案 0 :(得分:0)

document.cookie获取并设置与当前文档相关联的Cookie (Mozilla Developer Network)

您可以使用document.cookie全局使用vanilla JavaScript操作Cookie。

要存储多个Cookie,您必须多次分配document.cookie,例如存储var a = '1'; var b = '2'

document.cookie = "a=1";
document.cookie = "b=2";

要阅读Cookie字符串,只需引用document.cookie,例如console.log(document.cookie)

此外,您的帖子有几处编辑和语法错误。此外,这是一个可以通过Google搜索轻松解决的问题。