简体   繁体   English

在javascript中的html文件之间交换变量

[英]exchange variables between html files in javascript

I am trying to share variables between two html pages. 我正在尝试在两个HTML页面之间共享变量。 I am only using javascript and HTML5 to develop a windows 8 app. 我仅使用javascript和HTML5开发Windows 8应用程序。 Based on an image which a user clicks on one page, I want a div on a second page to be populated with that image. 基于用户单击一页上的图像,我希望第二页上的div填充该图像。 Any ideas? 有任何想法吗?

When I click on the image, I am currently calling the following function: 当我单击图像时,当前正在调用以下函数:

function imageClick(url) {
             //var id = parsed.ClientID;
             //window.location= url + "?" + id
             window.location = url;
         }

Then in my html file, I have this line: 然后在我的html文件中,有以下一行:

<img onclick="imageClick('pages/page2/page2.html')" 
data-win-bind="src:image" style="width: 133px; height: 125.5px;"> 

I was thinking of getting that id in the next page's url (if I were to uncomment the commented lines above) but it's a bit hackky and I don't actually know how to go about executing the retrieval of that on the next page.. 我当时正在考虑在下一页的url中获取该ID(如果要取消注释上面的注释行),但是这有点怪癖,我实际上不知道如何在下一页执行该ID的检索。

Is there a more efficient and easy way of doing this in javascript? 在javascript中,有没有更有效,更简便的方法? Like an equivalent of sessions in php or something? 像php中的会话一样?

Add the link to the image to the query part of the url when they click. 单击它们时,将指向图像的链接添加到URL的查询部分。 Something like you had in the comment, assuming you don't have a query part already: 假设您还没有查询部分,则您可以在注释中添加类似的内容:

function imageClick(url) {
         //var id = parsed.ClientID;
         window.location= url + "?src=" + url.src;
         //window.location = url;
     }

The other page can use window.location.search to extract it, strip off the src= . 另一页面可以使用window.location.search提取它,剥离src= The code would look something like this: 代码看起来像这样:

var src = window.location.search;
if (src.indexOf("src=") == 0) {
    src = src.substring(4);
}
newPageImageElement.src = src;

Where newPageImageElement is the <img> where you want to display the picture on the second page. 其中newPageImageElement是要在第二页上显示图片的<img>

Javascript does not have session variables because it runs on the client side. Javascript没有会话变量,因为它在客户端运行。 You can use URL parameters and cookies in order to achieve the same results. 您可以使用URL参数和cookie来获得相同的结果。

You can get the URL parameter by using this function: 您可以使用以下函数获取URL参数:

http://ziemecki.net/content/javascript-parsing-url-parameters http://ziemecki.net/content/javascript-parsing-url-parameters

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM