【发布时间】:2016-05-15 00:50:59
【问题描述】:
我正在练习使用 document.cookie 属性,并且能够在我的 FireFox 浏览器中设置和返回 cookie。但是,当我尝试在 google chrome 中返回一些 cookie 时,我没有返回任何东西。这有什么原因吗?这是我在jsfiddle 中的代码。
HTML
<div id="ex1">
<h2>Example 1</h2>
<p></p>
<h4>results:</h4>
<button id="btn">Return Cookie</button>
<button id="btn2">Set Cookie</button>
</div>
Javascript
function cText(text) {
return document.createTextNode(text);
}
function cElem(elem) {
return document.createElement(elem);
}
function attach(id, text, elem) {
var a = cText(text);
var b = cElem(elem);
b.appendChild(a);
var c = document.getElementById(id).appendChild(b);
return c;
}
document.getElementById('btn').onclick = function() {
var a = document.cookie;
attach('ex1', a, 'p');
}
/* In order to make key = values you have to make a separate line for
each name and value that you are going to put into the document.cookie*/
document.getElementById('btn2').onclick = function() {
document.cookie = "name = Michael Hendricks; expires =" + dayt + ";";
document.cookie = "occupation = Shitty Retail Clerk; expires =" + dayt + ";";
document.cookie = "age = 26 years old with big ol man boobs; expires =" + dayt + ";";
console.log('cookie has been saved');
}
【问题讨论】:
-
您的 jsfiddle 在我的 50.0.2661.102 Chrome 中运行良好
-
@Gosha_Fighten 是的,我看到它在 jfiddle 中有效。但是当我将它添加到常规 html 文件中并在 chrome 中输出时,我不会返回任何值。
标签: javascript html cookies