简体   繁体   English

将变量从javascript文件传递到另一个html页面

[英]passing variables from a javascript file to another html page

I have a variable value in one javascript file. 我在一个javascript文件中有一个变量值。 How do I access this variable in another html page, value when a user clicks that particular html link. 当用户点击特定的html链接时,如何在另一个html页面中访问此变量。 I have tried to use the concept of set and get cookies based on the variable, so that I can access this variable in another html page. 我试图使用set的概念并根据变量获取cookie,以便我可以在另一个html页面中访问此变量。 Is there any other way to achieve this ? 有没有其他方法来实现这一目标?

Use sessionStorage! 使用sessionStorage!

In the first page, initiate the value inside sessionStorage, for example I'm passing a userID value 24. Here's how you set it; 在第一页中,启动sessionStorage中的值,例如我传递一个userID值24.这是你如何设置它;

sessionStorage.userID = 24

Then, here's how to access it anywhere else; 然后,这里是如何在其他地方访问它;

console.log(sessionStorage.userID) // = 24

On logout, remember to clear it! 注销时,请记得清除它!

sessionStorage.clear()

You can also adapt the link to encode the information. 您还可以调整链接以对信息进行编码。 Change the href with javascript. 用javascript更改href。

Either add a query string: Or add a hash: 添加查询字符串:或添加哈希:

Second one might be safer as it doesn't depend on how your server handles queries, it should preserve the hash. 第二个可能更安全,因为它不依赖于服务器如何处理查询,它应该保留哈希。

Once on the new page use javascript again to get the info back from the current url using window.location 进入新页面后,再次使用javascript,使用window.location从当前网址获取信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将javascript变量从一个文件传递到另一个文件 - Passing javascript variables from one file to another 将变量从一个HTML页面传递到另一个HTML页面的最佳做法是什么? - What is the best practice for passing variables from one HTML page to another? 通过 JavaScript 将变量从一个 html 页面传递到另一个页面 - Passing Variable through JavaScript from one html page to another page 将javascript变量从一个html页面传递到另一页面 - Passing javascript variable from one html page to another page 将javascript变量从一个函数/文件传递到另一个 - Passing javascript variables from one function/file to another 如何使用另一个PHP文件中的变量将其包含在HTML页面javascript函数中 - How to use variables from another php file to include in a html page javascript function 将变量从 HTML 传递到使用 addEventListener 的 Javascript 文件 - Passing variables from HTML to Javascript file that uses addEventListener 将javascript对象变量从一个HTML页面传递到另一HTML页面 - Passing javascript object variable from one HTML page to another 将javascript变量传递到另一个php页面 - Passing javascript variables to another php page 使用本地存储将 html 页面中的 javascript 变量传递到另一个页面 - Pass javascript variables from a html page to another using local storage
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM