使用Javascript编写cookie(和奶油)的代码

Writing code for cookies (and cream) using Javascript

本文关键字:代码 Javascript 编写 cookie 使用      更新时间:2023-11-11

我正在做一项任务,我必须使用通过表单输入的值编写cookie,但我不知道如何从下拉菜单中获取所选值以保存为cookie。

Javascript

    /* this function attachs the event handler under both event models */
    function addEvent(object, evName, fnName, cap) {
        if (object.attachEvent)
            object.attachEvent("on" + evName, fnName);
        else if (object.addEventListener)
            object.addEventListener(evName, fnName, cap);
    }

    function writeCookie(cName, cValue, expDate, cPath, cDomain, cSecure) {
      if (cName && cValue != "") {
         var cString = cName + "=" + escape(cValue);
         if (expDate) 
            cString += ";expires=" + expDate.toGMTString();
         if (cPath) cString += ";path=" + cPath;
         if (cDomain) cString += ";domain=" + cDomain;
         if (cSecure) cString += ";secure";

         document.cookie = cString;
      }
    }
    function saveMailingInfo() {
      var expire = new Date();
      expire.setFullYear(expire.getFullYear() + 1);
      var allFields = document.mailingForm.elements;
      for (var i  = 0; i < allFields.length; i++) {
        if (allFields[i].type == "text") {
          writeCookie(allFields[i].id, allFields[i].value, expire);
        }
        if (allFields[i].nodename == "SELECT") {
          writeCookie(allFields[i].id, allFields[i].selectedIndex, expire);
        }
        if (allFields [i].type == "radio" || allFields[i].type == "checkbox") {
      writeCookie(allFields[i].id, allFields[i].checked, expire);
    }
      }
      alert("Registration data saved");
    }
    addEvent(window, "load", initPage, false);
    function initPage(){
      document.getElementById("sbutton").onclick = saveMailingInfo;
      document.getElementById("favoriteCake").selectedIndex = retrieveCookie("favoriteCake");
    }

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <!-- DW6 -->
    <head>
    <!-- 

    -->
    <title>Cakes by Emily</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="main.css" type="text/css" />
       <script type="text/javascript" src="cakeForm.js"></script>
    </head>
    <body >
    <div class="head" id="header">
      <p><img src="cake.jpg" alt="cake picture" /><img src="logo.gif" alt="Cakes by Emily" width="400" height="125" /></p>
      <div class="links" id="navigation">
        <a href="#">Home</a>
        <a href="#">Cakes</a>
        <a href="#">Pastries</a>
        <a href="#">Pies</a>
        <a href="#">Mailing List</a>
      </div>
    </div>
    <div class="mainContent">
    <p>Enter your info to be added to our email list with reminders about getting that birthday 
    cake you want! Remember at Cakes by Emily, we aim to make every birthday the best!</p>
    <form name="mailingForm" >
     <table>
      <tr>
       <td>
      First:
       </td>
       <td> <input type="text" name="firstName"  id="firstName"><BR>
      </td>
     </tr>
      <tr>
       <td>
      Last: 
       </td>
       <td><input type="text" name="lastName" id="lastName" ><BR>
      </td>
     </tr>
      <tr>
       <td>
      E-Mail: 
       </td>
       <td><input type="text" name="email" id="email" ><BR>
      </td>
     </tr>
      <tr>
       <td>
      Birthday (mm/dd/yyyy): 
       </td>
       <td><input type="text" name="birthday" id="birthday" ><BR>
      </td>
     </tr>
      <tr>
       <td>
      Favorite Cake: 
       </td>
       <td>
        <select id="favoriteCake">
         <option value="ButterCream">Butter Cream</option>
         <option value="Chocolate">Chocolate</option>
         <option value="Vanilla">Vanilla</option>
         <option value="RedVelvet">Red Velvet</option>
       </select><BR>
      </td>
     </tr>
      <tr>
       <td>
      Frequency of Emails: 
       </td>
       <td><input type="radio" name="frequency" id="frequency1" >Email me monthly<BR>
           <input type="radio" name="frequency" id="frequency2" >Email me quarterly<BR>
           <input type="radio" name="frequency" id="frequency3" >Email me near my birthday<BR>
      </td>
     </tr>
    </table>
    <input type="submit" id="sbutton" name="sbutton"  value="Join our mailing List" />
    <input type="reset" value="Reset the form" />
    </form>
    </div>
    <div class="footer">
    </div>
    </body>
    </html>

您可以使用选定的Index值属性获取选定的Item。

var cake = document.getElementById("favoriteCake");
var selectedCake = cake.options[cake.selectedIndex].value;

将其存储在cookie中的一种方法是:

document.cookie = "selected_cake="+selectedCake; 

要获取HTML select中所选项目的值,请使用:

var cake = document.getElementById("favoriteCake");
var cakeValue = cake.options[cake.selectedIndex].value;

我还忍不住注意到,当分支只包含一条语句时,大多数if语句都利用了可选的大括号:

    if (object.attachEvent)
        object.attachEvent("on" + evName, fnName);
    else if (object.addEventListener)
        object.addEventListener(evName, fnName, cap);

这里有一个很好的例子说明为什么你不应该这样做:

    if (cPath) cString += ";path=" + cPath;

这使得它看起来像是如果cPathtrue,那么同一行上的代码将被执行,但path=" + cPath;将始终被执行,因为当您省略大括号时,您告诉JavaScript运行时,当代码进入该分支时,只应执行测试或else之后的第一条语句。

这是一种极其糟糕的做法,最终会导致程序出现错误。总是用大括号包围你的分支代码:

    if (object.attachEvent){
        object.attachEvent("on" + evName, fnName);
    } else if (object.addEventListener) {
        object.addEventListener(evName, fnName, cap);
    }

和:

    if (cPath) { 
         cString += ";
         path=" + cPath;
    }

最后,使用跨浏览器事件连接功能:

/* this function attachs the event handler under both event models */
function addEvent(object, evName, fnName, cap) {
    if (object.attachEvent)
        object.attachEvent("on" + evName, fnName);
    else if (object.addEventListener)
        object.addEventListener(evName, fnName, cap);
}

您不仅应该包括大括号,还可以通过切换测试顺序来提高性能。由于attachEvent仅适用于IE 8及以下版本,因此您的测试是真实的,但您每次都要进行测试,这将是罕见的情况。如果您切换序列,您将很少需要运行else代码,而现在,您必须在大多数时间运行测试代码和else代码。最后,您只需要else,而不需要else if,因为如果其中一个事件模型不受支持,那么另一个就是-您不需要测试它

function addEvent(object, evName, fnName, cap) {
    if (object.addEventListener){
        object.addEventListener(evName, fnName, cap);
    } else {
        object.attachEvent("on" + evName, fnName);
    }          
}