简体   繁体   English

JavaScript修改一个文件中的变量并在另一个文件中读取它

[英]JavaScript modifying a variable in one file and reading it in another

Is there any way to modify a global var within a function and then using it in another page? 有没有办法在函数中修改全局变量然后在另一个页面中使用它? Let me explain better my situation: I have two HTML files, "Index.html" and "character.html". 让我更好地解释一下我的情况:我有两个HTML文件,“Index.html”和“character.html”。 In Index, I have related this JS code: 在Index中,我已经关联了这个JS代码:

var pcharacter = "initialValue";

document.getElementById("barbarianClass").onclick = function(event){
    event.preventDefault();
    pcharacter = "barbarian"; // the important line here...
    location.href = "pages/character.html";
}

The element "barbarianClass" is a link, that's why I blocked the default behavior with preventDefault() until I have given a value to my pcharacter var. 元素“barbarianClass”是一个链接,这就是为什么我用preventDefault()阻止了默认行为,直到我给了我的pcharacter var一个值。 Now, I have character.html, that has the following one single JS line code attached: 现在,我有character.html,它附加了以下一个单独的JS代码:

alert(pcharacter);

In character.html, I have both JS files related, how it should be done: 在character.html中,我有两个JS文件相关,它应该如何完成:

<script type="text/javascript" src="indexCode.js"></script>
<script type="text/javascript" src="charsCode.js"></script>

The problem is that when I click the link "barbarianClass" and my character.html page shows, the var pcharacter showed in the alert is "initialValue", even when I said it to have the value "barbarian" inside the event attached to the link before opening the page. 问题是,当我点击链接“barbarianClass”并且我的character.html页面显示时,警报中显示的变量字符是“initialValue”,即使我说它在附加到事件的事件中具有值“野蛮人”打开页面前链接。 Of course, I have plans for that variable, but for the question, the alert is easier. 当然,我有这个变量的计划,但对于这个问题,警报更容易。 Could someone, please, tell me why the initialValue is kept? 有人可以告诉我为什么保留initialValue? Is there any obscure rule in JS that says that when you load a JS document, global vars can't be changed anymore or something like that? 在JS中是否有任何模糊的规则说当你加载JS文档时,全局变量不能再被更改或类似的东西? I doesn't make any sense... 我没有任何意义......

You can save data in cookie 您可以将数据保存在cookie中

function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires="+d.toUTCString();
  document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i=0; i<ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1);
    if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
  }
  return "";
}

http://www.w3schools.com/js/js_cookies.asp http://www.w3schools.com/js/js_cookies.asp

your code will be 你的代码将是

/*save data*/
document.getElementById("barbarianClass").onclick = function(event){
  event.preventDefault();
  setCookie('pcharacter', 'barbarian', 1)
  location.href = "pages/character.html";
}

/*get data*/
alert(getCookie('pcharacter'));

What you are trying to do is simply not possible with variables alone , as for the reason highlighted by someone in your comments 你想要做的就是单独使用变量是不可能的,因为你的评论中有人强调了这一点

Lets assume this is possible - would you want the page that has your bank details being accessed via javascript variables on a different page? 让我们假设这是可能的 - 您是否希望通过其他页面上的javascript变量访问您的银行详细信息的页面?

You should use cookies (client-side) or sessions(server-side) to accomplish this task. 您应该使用cookie(客户端)或会话(服务器端)来完成此任务。 This is how you set a cookie in javascript: 这是你在javascript中设置cookie的方法:

document.cookie = "pcharacter=barbarian"

and then you can access this cookie in all other pages by this simple function : 然后你可以通过这个简单的函数访问所有其他页面中的这个cookie:

function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1);
    if (c.indexOf(name) == 0) return    
    c.substring(name.length,c.length);
}
return "";
}

console.log(getCookie("pcharacter"));

You can also set an expiry time for your cookies . 您还可以设置Cookie的到期时间。

Ummmmmmm...well....banking problems aside :-) 嗯......好吧......银行问题放在一边:-)

To answer your question - the answer is both yes and no. 回答你的问题 - 答案是肯定和否定。 If what you are going to do is to directly load in a new web page then no - your global variables will disappear like cotton candy at a carny show. 如果你要做的是直接加载到一个新的网页然后没有 - 你的全局变量将像棉花糖一样在一个carny show中消失。

BUT! 但! If instead, you use jQuery's getScript() function, then you can load in a new web page and keep your global variables. 相反,如果使用jQuery的getScript()函数,则可以加载新的网页并保留全局变量。 All you have to do is to convert your incoming web page into hexadecimal so all of the different letters like the less than sign, single, and double quotes don't muck things up, unconvert it once you have it, and then replace your web page or insert your web page/part as you wish. 您所要做的就是将传入的网页转换为十六进制,这样所有不同的字母(如小于号,单引号和双引号)都不会破坏,一旦拥有它就会转换,然后替换您的网页页面或插入您的网页/部分,如您所愿。

To convert it to hex all you need is the bin2hex() function in PHP. 要将其转换为十六进制,您只需要PHP中的bin2hex()函数。 To unhex something in Javascript you can go and get my toHex() and fromHex() functions on GitHub. 要在Javascript中取消某些内容,您可以在GitHub上获取我的toHex()和fromHex()函数。

Also, you might want to think about sending everything back to the server in hex as well so script kiddies have a bit harder time giving themselves a +1000 weapon. 此外,您可能还想考虑将所有内容以十六进制形式发送回服务器,因此脚本小子在给自己+1000武器时会有点困难。 Just a thought. 只是一个想法。 It won't slow them down a lot - but every little bit helps. 它不会减慢它们的速度 - 但每一点点都有帮助。 :-) :-)

You can use localStorage to pass data from one file to another. 您可以使用localStorage将数据从一个文件传递到另一个文件。 The basic syntax is: 基本语法是:

if (typeof(Storage) !== "undefined") {
    // Code for localStorage/sessionStorage.
} else {
    // Sorry! No Web Storage support..
}

Setting a value: 设定值:

localStorage.setItem('myObj', 'My Object');

And getting a value: 获得一个价值:

localStorage.getItem('myObj');

If localStorage is not supported, you can always fall back to one of the cookies or URL rewriting. 如果不支持localStorage,您可以随时回退到其中一个cookie或URL重写。 otherwise you can use window.name also 否则你也可以使用window.name

暂无
暂无

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

相关问题 将包含字符串的JavaScript变量读取到另一个文件中 - Reading a javascript variable containing a string into another file 在另一个 javascript 文件中引用变量 - Referencing variable from one javascript file in another 将变量从一个 javascript 获取到另一个 php 文件中的另一个 javascript - Get variable from one javascript to another javascript in another php file 如何将一个JavaScript文件中的一个变量调用到另一个JavaScript文件中? - How to call one variable in a JavaScript file to another JavaScript file? 如何将一个JavaScript文件中的变量访问/获取到另一个JavaScript文件中 - how to access/get the variable in one javascript file to another javascript file 将变量从一个javascript文件传递到另一个javascript文件 - pass a variable from one javascript file to another javascript file 读取 CSV 文件并将名称写入一个数组并将值写入 Javascript 中的另一个数组 - Reading CSV file and writing names to one array and values to another in Javascript 如何将一个JavaScript变量调用到另一个JavaScript文件 - How to call one javascript variable to another javascript file 是否可以在一个javascript文件中声明一个变量并在另一个javascript文件中使用它? - Is it possible to declare a variable in one javascript file and use it in another one? 有没有办法在javascript中将变量或函数从一个文件获取到另一个文件? - Is there a way to get a variable or function from one file to another file in javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM