将数据推送到javascript数组但数组没有增长

时间:2012-03-07 23:44:53

标签: javascript html url push

我正在尝试为内部网站创建导航系统。

为此,我正在通过跟踪页面网址的javascript创建一个数组,并且每个新页面都会将新网址推送到数组中。

问题是,每个新页面似乎都覆盖了最后一页。

这是我的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>

它会根据需要显示URL(last_element),但是当我浏览页面而不是上升到2,3,4等时,number_rows保持为1,这是我希望实现的目标。

任何人都可以给我任何指示吗?

2 个答案:

答案 0 :(得分:1)

每次刷新页面时,JavaScript都会重新刷新。如果您需要数据持久性,则需要使用cookie,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);
}());

答案 1 :(得分:0)

在页面之间浏览时,会在每个页面上重新创建javascript环境。所以你总是从一个空数组开始。