我有两个页面 - “第 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 函数并将我正确重定向到我的页面 2。
但第二页上有这个:
window.onload=read_price();
我总是得到全局变量价格的“未定义”值。
我已经阅读了很多有关这些全局变量的内容。例如。在这个页面:全局变量的问题.. https://stackoverflow.com/questions/9085839/surprised-that-global-variable-has-undefined-value-in-javascript但我无法让它工作...
为什么这不起作用?
无需阅读您的代码,而只需阅读您的场景,我将通过使用来解决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 允许更多空间,并且当您请求页面时它们不会发送回服务器。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)