如何用js操作cookie

how to manipulate cookie with js

这里的代码只存储选项,最后它从 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>

document.cookie: 获取和设置与当前文档关联的 cookies (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)

此外,您的 post 有几个编辑和语法错误。此外,这个问题可以通过 Google 搜索轻松回答。