通过 JavaScript 将变量从一个 html 页面传递到另一个页面

编程入门 行业动态 更新时间:2024-10-28 03:31:11
本文介绍了通过 JavaScript 将变量从一个 html 页面传递到另一个页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两页 - 第 1 页"和第 2 页".在第 1 页上有一个文本框,其值为例如100 和最后一个按钮.

I have two pages - "page 1" and "page 2". On page 1 there's an text-box with a value of e.g. 100 and a button at the end.

通过按下按钮,我希望 javascript 将文本框的值保存在全局 (?) 变量中并跳转到第 2 页.使用window.onload"我想要第二个 Javascript 函数来提醒保存在第 1 页的值.

By pressing the button I want javascript to save the value of the textbox in a global (?) variable and jump to page 2. With "window.onload" I want a second Javascript-function to alert the value saved at page1.

这是我的 Javascript 代码:

Here's my Javascript code:

<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 页"我有这个发送按钮:

On "page 1" I have this send-Button with:

<input class="button_send" id="button_send" type="submit" value="Submit_price" onclick="save_price();"/>

它启动 Javascript 功能并将我正确重定向到我的 page2.

It starts the Javascript function and redirects me correctly to my page2.

但是在第二页上:

window.onload=read_price();

我总是得到全局变量价格的未定义"值.

I always get an "undefined" value of the global variable price.

我已经阅读了很多关于这些全局变量的内容.例如.在此页面:全局变量的问题..但我无法让它工作......

I've read a lot about those global variables. E.g. at this page: Problem with global variable.. But I can't get it working...

为什么这不起作用?

推荐答案

不用阅读你的代码,只阅读你的场景,我会使用 localStorage 来解决.这是一个例子,我将使用 prompt() 简称.

Without reading your code but just your scenario, I would solve by using localStorage. Here's an example, I'll use prompt() for short.

在第 1 页:

window.onload = function() { var getInput = prompt("Hey type something here: "); localStorage.setItem("storageName",getInput); }

在第 2 页:

window.onload = alert(localStorage.getItem("storageName"));

您也可以使用 cookie,但 localStorage 允许更多空间,并且在您请求页面时它们不会发送回服务器.

You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.

更多推荐

通过 JavaScript 将变量从一个 html 页面传递到另一个页面

本文发布于:2023-05-25 10:59:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/226675.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词库加载错误:Could not find file &#039;D:\淘小白 高铁采集器win10\Configuration\Dict_Sto

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!