如何使用 JavaScript 僅為主頁設定 cookie?


要為主頁設定 cookie,請將頁面新增到主頁本身。

示例

你可以嘗試執行以下程式碼來設定 cookie

線上演示

<html>
   <head>
      <script>
         <!--
            function WriteCookie() {
               if( document.myform.customer.value == "" ){
                  alert("Enter some value!");
                  return;
               }
               cookievalue= escape(document.myform.customer.value) + ";";

               var myPath = window.location.pathname;
               var address = query.split("/");

               if ((address[address.length - 1]).toLowerCase() == "home.html") {
                  document.cookie = "name=" + cookievalue;
                  document.write ("Setting Cookies : " + "name =" + cookievalue);
               }
            }
         //-->
      </script>
   </head>
   <body>
      <form name = "myform" action="">
         Enter name: <input type="text" name="customer"/>
         <input type="button"  value="Set Cookie"  onclick="WriteCookie();"/>
      </form>
   </body>
</html>

更新於: 2020 年 1 月 9 日

268 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.