我正在尝试为一个内部网站创建一个导航系统。
为此,我通过javascript创建了一个数组,用于跟踪页面的url,并且对于每个新页面,我将新的url推入数组。
问题是,每个新页面似乎都覆盖了最后一个页面。
这是我的javascript文件中的内容...请注意,我只在数组不存在时创建一个新数组(当用户离开网站时,它将被删除)。
var myURL = document.URL;
if (typeof myHistory == "undefined" || !(myHistory instanceof Array)) {
var myHistory = [];
}
myHistory.push(myURL);
var last_element = myHistory[myHistory.length - 1];
var number_rows = myHistory.length;这就是我用来查看html中的值的地方。
<script type="text/javascript">
<!--
document.write(last_element);
document.write(number_rows);
// -->
</script>它根据需要显示网址(last_element),但当我在页面之间浏览时,number_rows仍然是1,而不是我希望达到的2、3、4等。
有谁能给我点建议吗?
发布于 2012-03-08 07:49:28
每次刷新页面时,JavaScript都会重新刷新。如果需要数据持久化,则需要使用cookies、localStorage或服务器端数据存储。
所有这些选项都需要序列化和反序列化字符串。
下面是一个快速示例,说明如何使用localStorage完成此操作
//closure to prevent global pollution
//it's good to be green
(function () {
"use strict";
var history,
url;
//set url here
//I'm making the assumption that no url will have a ',' char in it
history = localStorage['history'].split(',');
history.push(url);
localStorage['history'] = history.join(',');
console.log(url, history.length);
}());发布于 2012-03-08 07:50:46
当您在页面之间浏览时,会在每个页面上重新创建javascript环境。所以你总是从一个空数组开始。
https://stackoverflow.com/questions/9610910
复制相似问题