简体   繁体   English

是否可以从JQuery函数中访问常规javascript变量?

[英]Is it possible to access a regular javascript variable from within a JQuery function?

I have an HTML file which imports two files: 我有一个导入两个文件的HTML文件:

graph.js and main.js graph.js和main.js

The main file contains logic which accesses a phone's accelerometer/records acceleration and it is a purely javascript file. 主文件包含访问手机加速度计/记录加速度的逻辑,它是纯JavaScript文件。 The Graph.js file contains a single JQuery function $(.....) Graph.js文件包含单个JQuery函数$(.....)

Is it possible to access a variable in main.js from graph.js? 是否可以从graph.js访问main.js中的变量?

Yes jQuery is written in JavaScript and it can access any variable declared in that page via import of other JavaScript files. 是的,jQuery 用JavaScript编写的,并且可以通过导入其他JavaScript文件来访问该页面中声明的任何变量。 As you are trying to access variable in onload of document, I don't see any problem, because other scripts should already have been loaded before that. 当你试图在访问变量onload的文件,我看不出有什么问题,因为其他脚本应该已经被之前加载。

是。

如果在全球范围内,是的。

It should be, so long as the main.js loads first and if you set it as a global variable. 只要首先加载main.js并将其设置为全局变量,就应该如此。

You make a global variable by creating it outside of a function. 您可以在函数外部创建全局变量。 If needed, you can create it outside a function, then set it inside a function in the main.js file. 如果需要,可以在函数外部创建它,然后在main.js文件中的函数内部设置它。

You can freely share variables between different JS files (a jQuery file is just a JS file) in several different ways: 您可以通过几种不同的方式在不同的JS文件(jQuery文件只是一个JS文件)之间自由共享变量:

  1. Define the variables in the global scope, then they can be accessed anywhere. 在全局范围内定义变量,然后可以在任何地方访问它们。
  2. Define variables on the window object. 在窗口对象上定义变量。 This makes them globally accessible even if your code defining the variables isn't in the global scope. 即使定义变量的代码不在全局范围内,这也使它们可以全局访问。
  3. Define variables as properties on any object that you can get to from your code. 将变量定义为可从代码获取的任何对象上的属性。 So, if you have a global config object called myConfig , you could define properties on it like myConfig.count = 0; 因此,如果您有一个名为myConfig的全局配置对象,则可以在其上定义属性,例如myConfig.count = 0; and you can then access myConfig.count from anywhere. 然后您可以从任何地方访问myConfig.count This is often referred to as namespacing and creates only a single global object which you then add multiple properties to. 通常将其称为命名空间,仅创建一个全局对象,然后向其中添加多个属性。
  4. Define a globally accessible function that returns your data that you can call from anywhere. 定义一个全局可访问的函数,该函数返回可以在任何地方调用的数据。

When designing how this works, remember that it's generally better to introduce as few globally accessible symbols as possible because each one is an opportunity for a conflict with some other code in the page. 在设计其工作方式时,请记住,通常最好引入尽可能少的全局可访问符号,因为每个符号都是与页面中其他代码冲突的机会。

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

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