我有两页 - “第1页”和“第2页”。在第1页上,有一个文本框,其值为例如100和最后一个按钮。
按下按钮我希望javascript将文本框的值保存在全局(?)变量中并跳转到第2页。使用“window.onload”我想要第二个Javascript函数来提醒第1页保存的值
这是我的Javascript代码:
<script type="text/javascript">
var price; //declare outside the function = global variable ?
function save_price(){
alert("started_1"); //just for information
price = document.getElementById('the_id_of_the_textbox').value;
alert(price); //just for information
}
<script type="text/javascript">
function read_price(){
alert("started_2");
alert(price);
}
在“第1页”,我有这个发送按钮:
<input class="button_send" id="button_send" type="submit" value="Submit_price" onclick="save_price();"/>
它启动Javascript功能并将我正确地重定向到我的page2。
但是在第二页上有这个:
window.onload=read_price();
我总是得到全球变量价格的“未定义”值。
我已经阅读了很多关于那些全局变量的内容。例如。在这个页面:Problem with global variable..但我不能让它工作......
为什么这不起作用?
答案 0 :(得分:35)
如果不阅读您的代码而只阅读您的方案,我会使用localStorage
来解决。
这是一个例子,我将简称prompt()
。
在第1页:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
第2页:
window.onload = alert(localStorage.getItem("storageName"));
您也可以使用Cookie,但localStorage允许更多空格,并且在您请求网页时它们不会被发送回服务器。
答案 1 :(得分:6)
这里最好的选择是使用查询字符串来“发送”该值。
how to get query string value using javascript
如果这不仅仅是一个学习练习,你可能想要考虑这个的安全含义。
全局变量在这里不会帮助你,因为一旦重新加载页面,它们就会被销毁。
答案 2 :(得分:1)
您有几种不同的选择:
答案 3 :(得分:1)
共有两页: Pageone.html:
<script>
var hello = "hi"
location.replace("http://example.com/PageTwo.html?" + hi + "");
</script>
PageTwo.html:
<script>
var link = window.location.href;
link = link.replace("http://example.com/PageTwo.html?","");
document.write("The variable contained this content:" + link + "");
</script>
希望有帮助!