HTML5本地存储项目未保存相关

我正在尝试从url查询字符串中保存一个值,该字符串需要插入到用户导航到的任何页面的表单中,但到目前为止,我无法让代码通过包含原始查询的初始登录页面串。

使用此方法获取X的查询字符串值,并将其保存在localStorage中以获取密钥Xcode:

 var field = 'x'; var url = window.location.href; if(url.indexOf('?' + field + '=') != -1) { function getUrlVars() { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; } var user_code = getUrlVars()["x"]; if (localStorage) { localStorage.setItem("xcode",user_code); }  

然后使用它将它插入到类.xcode-field的任何输入的“value”属性中:

  window.onload = function() { var thecode = localStorage.getItem("xcode"); if (thecode != "undefined" && thecode != "null") { $(".xcode-field").attr("value",thecode); } else { $(".xcode-field").attr("value","default"); } }  

如果该项不在LocalStorage中,则应插入默认值(或者它应该什么也不做,但不确定如何设置它。)

我现在的问题是,这适用于用户登陆的页面(example.com/?x=1234),但当他们导航到任何其他页面时,表单中的值将填充“undefined”。 因此,查询字符串值也没有被正确存储,上面的else语句也不能插入“default”。 知道我在这里做错了吗? 谢谢!

小提琴(但似乎没有在那里工作): http : //jsfiddle.net/08suhbuk/

更新:终于明白了! LocalStorage正在连续页面上重置,因为初始查询字符串解析和setItem将在每个页面上重复并覆盖原始值。 我通过添加以下代码来解决它,以检查第一个脚本周围是否存在查询字符串:

 var field = 'x'; var url = window.location.href; if(url.indexOf('?' + field + '=') != -1) { 

编辑的最终工作代码。