【发布时间】:2015-01-04 12:49:11
【问题描述】:
我有两页 - “第 1 页”和“第 2 页”。在第 1 页上有一个文本框,其值为例如100,最后一个按钮。
通过按下按钮,我希望 javascript 将文本框的值保存在全局 (?) 变量中并跳转到第 2 页。使用“window.onload”我想要第二个 Javascript 函数来提醒保存在 page1 的值.
这是我的 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();
我总是得到一个全局变量 price 的“未定义”值。
我已经阅读了很多关于这些全局变量的信息。例如。在这个页面上:Problem with global variable.. 但我无法让它工作......
为什么这不起作用?
【问题讨论】:
-
您误解了浏览器中 JavaScript 中的“全局变量”是什么。它们仍然与设置它们的页面相关联,它们不存在于其他页面中。
-
全局变量只对页面是全局的。也许看看url参数stackoverflow.com/questions/979975/…?
-
@CBroe(和 nha)谢谢!不知道他们仍然被绑在页面上。我认为它们是“真正的”全球性的(适用于所有网页)
标签: javascript html variables undefined global