我正在练习制作电子商务网站。我正在努力将我的javascript变量传递到购物车页面和结帐页面之间。我试过这个例子:
page one:
<a href="example2.html?myVar1=42&myVar2=66" >LINK</a>
page 2:
var qs = new Querystring();
var v1 = qs.get("myVar1");
var v2 = qs.get("myVar2");
我无法让它工作,因为我的网页引发了一个关于无法识别QueryString的错误,所以我目前正在尝试使用window.localStorage,如下所示:
Page 01:
<button class="checkout" type="button" onClick="window.location.href='checkout.html'; window.localStorage.setItem("total",total)">Checkout</button>
Page 2:
var name = window.localStorage.getItem("total");
答案 0 :(得分:1)
要修复您的第一个方法(通过查询字符串在页面之间传递变量),您可能需要以下内容:
// page one:
<a href="example2.html?myVar1=42&myVar2=66" >LINK</a>
// page 2:
var query = window.location.search;
if( typeof query !== 'undefined' ) {
var params = {},
parts
;
// take off the ? and split into groups of key=value strings
query = query.replace('?','').split('&');
// split key=value strings into a usable object
for(var i=0;i<query.length;i++){
parts = query[i].split('=');
params[ parts[0] ] = parts[1];
}
// now access your variables like so:
params.myVar1 // is now "42" (a string)
params.myVar2 // "66"
}