简体   繁体   English

在nodejs中的两个html文件之间访问共享javascript变量的最佳方法是什么

[英]what is the best way to access the shared javascript variable between two html files in nodejs

I'm new to node.js. 我是node.js的新手。 I have two html files and one shared common.js. 我有两个html文件和一个共享的common.js。 In index1.html, when anchor button is clicked it calls changetest() function of common.js(which updates test variable). 在index1.html中,当单击定位按钮时,它将调用common.js的changetest()函数(更新测试变量)。 now i want to use the updated variable in index2.html. 现在我想在index2.html中使用更新的变量。 But index2.html picks the original value of test. 但是index2.html会选择test的原始值。 (which may be because in new page index2.html reloads the common.js) please help what can be the good way of passing and receiving test value in index2.html. (这可能是因为在新页面中index2.html重新加载了common.js),请提供帮助,这可能是在index2.html中传递和接收测试值的好方法。

Index1.html Index1.html

<html>
    <head>
        <script type="text/javascript" src="common.js"></script>
    </head>
    <body>
        <h1>Sample Page</h1>
        <a href="index2.html" onclick="changetest()">Navigate</a>
    </body>
</html>

common.js common.js

var test="abc";

function changetest(){
    test = "xyz";
}

index2.html index2.html

<html>
    <head>
        <script type="text/javascript" src="common.js"></script>
    </head>
    <body>
        <h1>Sample Page2</h1>
        <a href="#"><script>document.write(test)</script></a>
    </body>
</html>

I would reccomend use https://developer.mozilla.org/en/docs/Web/API/Window/localStorage 我建议使用https://developer.mozilla.org/en/docs/Web/API/Window/localStorage

With it you can easily set and get data from user browser. 有了它,您可以轻松设置并从用户浏览器获取数据。

To use it just do like this 要使用它就像这样

localStorage.setItem('test', 'My test value');

alert( "test= " + localStorage.getItem("test"));

https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage https://developer.mozilla.org/zh-CN/docs/Web/API/Storage/LocalStorage

Hope this helps. 希望这可以帮助。

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

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