简体   繁体   English

在JavaScript中设置其他JavaScript变量

[英]Setting a variable of a javascript from an other, in javascript

I have the following problem: 我有以下问题:

In file (let a.js be) I have: 在文件中(让a.js是),我有:

var kindofdisplay ;

In an other file ( let b.js be) I get the information to set kindofdisplay . 在另一个文件(让b.js是)中,我获得了设置kindofdisplay的信息。 Now, I would like to set kindofdisplay from file b.js so that when a.js is executed it will be able to process the variable in a correct way. 现在,我想从文件b.js设置kindofdisplay ,以便在执行a.js时能够以正确的方式处理变量。

Many thanks 非常感谢

As Raja pointed out. 正如Raja指出的。 If you can access the kindofdisplay variable on b.js, you can change it. 如果可以访问b.js上的kindofdisplay变量,则可以对其进行更改。 You just need to take care not to declare it again. 您只需要注意不要再次声明它。

You can try give a default value like: 您可以尝试提供一个默认值,例如:

var kindofdisplay='none';

And check if that's the value the variable has when on b.js. 并检查b.js上变量是否具有该值。 If it's not, you are probably declaring it again. 如果不是,您可能会再次声明。

If you're using the two javascript files on different web pages, you could always set the variable as a cookie (providing you don't need it to be secure). 如果您在不同的网页上使用两个javascript文件,则始终可以将变量设置为cookie(前提是您不需要它是安全的)。

Have a look at this tutorial about cookies. 看一下有关cookie的本教程

Another way to do this would be to put the script that defines the function for setting the variable in one file, link it to both pages that you need the variable to exist in and call the function on each page. 另一种方法是将定义用于设置变量的函数的脚本放在一个文件中,将其链接到需要变量存在的两个页面,然后在每个页面上调用该函数。

Of course, as a couple of people have already explained, if you're using the two javascript files on the same page, there's no need to do this - just ensure that the variable has the appropriate scope. 当然,正如几个人已经解释的那样,如果您在同一页面上使用两个javascript文件,则无需这样做-只需确保变量具有适当的作用域即可。

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

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