使用JavaScript打开另一个html页面时传递变量 [英] Passing variable when opening another html page using JavaScript

查看:98
本文介绍了使用JavaScript打开另一个html页面时传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常愚蠢的问题,但我无法在任何地方在网上找到它,并且我一直在寻找至少一个小时。

This is probably a really silly question, but I can't find it online anywhere and I've been looking for at least an hour.

我有一个链接< a href =MusicMe.htmlid =instrumentsNav>乐器< / a> 我想要点击它的ID,因为我需要将一些变量传递给我打开的页面以知道文档链接已被点击。这是从 productInformation.html

I have a link <a href="MusicMe.html" id="instrumentsNav">Instruments</a> which I want to get the ID of it once clicked, as I need to pass some variable to the page I am opening to know that the instruments link was clicked. This is being called from productInformation.html

中调用的。我也尝试了< a然后在我的JavaScript中, window.open(MusicMe。)。 html,_self); 然后尝试传递一个变量,但仍然没有运气。任何关于如何在打开页面时将变量传递回页面的帮助都很棒。

I have also tried doing <a href="#" onclick="instrumentsClick()" id="instrumentsNav">Instruments</a> and then in my JavaScript, window.open("MusicMe.html", "_self"); and then tried passing a variable that way, but still absolutely no luck. Any help as to how I would pass a variable back to the page when it opens would be brilliant.

打开后,我使用变量来设置ID一个元素,所以它只显示一组信息,它正在处理它自己的信息,但是当我回去尝试调用它时,它总是认为它显示了所有信息,因为我无法确定如何将变量设置为定义它。不幸的是我需要使用JavaScript而不是PHP。

Once it opens, I am using the variable to set the ID of an element so it only displays a certain set of the information, which is working on it's own, but when I go back to try and call it, it's always thinking it is showing them all as I cannot work out how to set the variable to define it. Unfortunately I need to use JavaScript not PHP.

谢谢。

Thanks.

推荐答案

我会告诉你一些方法,希望你能够实现它:

I would just tell you some ways, hope you would be able to implement it:


  1. 使用查询参数传递变量。 li>
  1. Use query params to pass the variable.

当您导航到另一个页面时,将查询参数添加到该URL。

When you're navigating to another page, add query params to the url.

window.open("MusicMe.html?variable=value", "_self");

在下一页中,通过获取 window.location.href来检查queryParam 并使用正则表达式在之后拆分params并获取该数据。

In your next page, check for queryParam by getting window.location.href and using regex to split the params after ? and get that data.


  1. 使用localStorage / cookies

在导航到下一页之前,在您的localStorage

Before navigating to the next page, set a variable in your localStorage

localStorage.setItem("variable","value");
window.open("MusicMe.html", "_self");

在第二页中,在窗口加载事件中。

In your second page, in the window load event.

 $(function() {
      if(localStorage.getItem("variable")) {

       // set the ID here
       // after setting remember to remove it, if it's not required
       localStorage.removeItem("variable");
      }

  });

这篇关于使用JavaScript打开另一个html页面时传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆