【发布时间】:2016-10-19 01:19:54
【问题描述】:
我使用一些 JavaScript 为网站制作了一个按钮点击计数器。 计数器运行良好,但现在我坚持保存计数。你知道,如果我点击按钮 3 次,文本会显示 3 次。但我想保存该值,因此如果用户刷新页面,它应该再次显示 3 次。
我知道使用 localStorage,我遵循了一个简单的教程并将其应用到我的代码中,但它似乎不起作用。当我在 Microsoft Edge 中运行该页面并看到调试页面 (F12) 时,控制台会抛出一个错误,上面写着:Unable to get property 'getItem' of undefined or null reference。我搜索了其他帖子,但没有一个可以解决我的问题。检索 localStorage 中的值时似乎卡住了。
这是我的代码:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Increment count when button is clicked</title>
</head>
<body>
<input type="button" value="Registrar" id="countButton" />
<input id="ocityField" type="text" value="" placeholder="Ciudad de Origen"/>
<input id="cityField" type="text" value="" placeholder="Ciudad de participación"/>
<input id="name" type="text" value="" placeholder="Nombre"/>
<p>Personas Registradas: <span id="displayCount">0</span></p>
<script type="text/javascript">
var count = 0;
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
var textbox = document.getElementById("ocityField");
var textboxa = document.getElementById("cityField");
var textboxb = document.getElementById("name");
if(window.localStorage.getItem('count')){
var savedcount = window.localStorage.getItem('count');
count = window.localStorage.getItem('count');
}else{
count = 0;
}
display.innerHTML = count;
button.onclick = function(){
var mystring = textbox.value;
var mystring2 = textboxa.value;
var mystring3 = textboxb.value;
if(!mystring.match(/\S/) || !mystring2.match(/\S/) || !mystring3.match(/\S/)) {
alert ('Empty value is not allowed');
return false;
} else {
count++;
window.localStorage.setItem('count', count);
display.innerHTML = count;
textbox.value = "";
textboxa.value = "";
textboxb.value = "";
return true;
}
}
</script>
</body>
</html>
我尝试使用 window.localStorage 和 localStorage,但没有人使用。
【问题讨论】:
-
你在其他浏览器上试过吗?
-
是的,我尝试过 Google Chrome、Safari 和 IE9。得到同样的错误。
-
你在本地浏览吗?
-
html,javascript在问题返回预期结果plnkr.co/edit/d7g5423KZVhUFuzuNnQN?p=preview -
@SoonKhai 是的,我正在本地浏览。