分裂的cookie串不起作用

时间:2018-03-01 18:56:23

标签: javascript

考虑到这是HTML代码,



function changeColor(){
       var selectedColor = document.getElementById("selectColor").value;
       if(selectedColor != "selectTheColor"){
          document.bgColor = selectedColor;
          document.cookie = "color="+selectedColor+";expires=Fri, 2 Mar 2018 02:00:00 UTC";
          var splited = document.cookie.split("="); // codes here not working
          alert(splited[1]);
       }
    }

<select value="bgColor" id="selectColor" onchange="changeColor();">
          <option value="selectTheColor">Select color</option>
          <option value="black">Black</option>
          <option value="blue">Blue</option>
          <option value="red">Red</option>
    </select>
&#13;
&#13;
&#13;

为什么代码不能解析?

1 个答案:

答案 0 :(得分:1)

这种方式不支持在一行以上分配字符串(使用'',你必须使用``代替)。请改为:

function changeColor(){
   var selectedColor = document.getElementById("selectColor").value;
   if(selectedColor != "selectTheColor"){
      document.bgColor = selectedColor;
      var test = "color="+selectedColor+`;expires=Fri, 2 Mar 2018 
      02:00:00 UTC`;
      var splited = test.split("="); // codes here not working
      alert(splited[1]);
   }
}
<select value="bgColor" id="selectColor" onchange="changeColor();">
      <option value="selectTheColor">Select color</option>
      <option value="black">Black</option>
      <option value="blue">Blue</option>
      <option value="red">Red</option>
</select>