HTML js和制作cookie

时间:2018-11-15 06:25:19

标签: javascript html

我需要通过html中的js制作基本的cookie。 js必须位于名为javascript.js的单独文件中,而在html中,我需要调用该函数来制作和存储Cookie。我有

<head>
<script type="text/javascript" src="javascript.js"></script>
</head>

在我的身体上创建源文件之前。我有一个按钮试图调用函数getCookie,所以在我的体内,我得到了

<button onclick="js.getCookie">COOKIE</button>

应该有一个弹出窗口询问我的名字,但我不确定为什么它不起作用。

js文件

function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
        c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
    }
}
return "";
}

function checkCookie() {
var user = getCookie("username");
if (user != "") {
    alert("Welcome again " + user);
} else {
    user = prompt("Please enter your name:", "");
    if (user != "" && user != null) {
        setCookie("username", user, 365);
    }
}
}

它是https://www.w3schools.com/js/js_cookies.asp的基础,因为我试图理解Cookie

1 个答案:

答案 0 :(得分:0)

当您在html中使用内联js函数时,还需要在其后加上括号。我已经将您的代码粘贴到了一段代码中,并使函数调用正常工作。

function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  var expires = "expires=" + d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function checkCookie() {
  var user = getCookie("username");
  if (user != "") {
    alert("Welcome again " + user);
  } else {
    user = prompt("Please enter your name:", "");
    if (user != "" && user != null) {
      setCookie("username", user, 365);
    }
  }
}
<body>
<button onclick="checkCookie();">COOKIE</button>
</body>