如何使 JavaScript 中的所有函数都可以访问变量?

发布于 2025-01-01 15:27:47 字数 803 浏览 1 评论 0原文

我很好奇这段代码片段中我不理解的内容......

为什么这有效?

 function insert_number(number){
   var output = document.getElementById('output');
   output.value += number.value;
 }

但这不起作用?

var output = document.getElementById('output');

function insert_number(number){
  output.value += number.value;
}

这与变量 output 的定义方式有关吗?

另外,我如何在函数 insert_number() 中编写 output 变量,同时仍然使 output 可用于脚本中的所有其他函数(即使这意味着必须将变量转义出函数,或者专门将其作为参数发送到另一个函数)?

注意:我的所有代码都位于外部“.js”文件中,

目前代码的完整上下文是这样的(稍后我将添加更多内容):

var output = document.getElementById('output');

function insert_number(number){
  output.value += number.value;
}

function clear_output(){
  output.value = "";
}

I'm curious about what I'm not understanding in this code snippet...

Why does this work?

 function insert_number(number){
   var output = document.getElementById('output');
   output.value += number.value;
 }

but this doesnt work?

var output = document.getElementById('output');

function insert_number(number){
  output.value += number.value;
}

Does it have something to do with the way the variable output is defined?

Also how would I write the output variable within the function insert_number() while still making output available to all other functions in my script (even if it means having to escape the variable out of the function, or specifically send it to another function as a parameter)?

Note: All my code is in an external ".js" file

the complete context of the code as of right now is this (I will be adding more later):

var output = document.getElementById('output');

function insert_number(number){
  output.value += number.value;
}

function clear_output(){
  output.value = "";
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

眼眸里的那抹悲凉 2025-01-08 15:27:47

这是一个在全局范围内仅保留单个对象/命名空间的解决方案:

(function(global, d) {
    var output = d.getElementById('output'),
        myApi = {};

    myApi.insert_number = function(number){
      output.value += number.value;
    };

    //export your api to the global scope
    global.myApi = myApi;
})(window, document);

现在您可以调用 myApi.insert_number(5); 您现在拥有一个可以访问输出的闭包 变量,以便您可以向 API 添加附加功能,而无需每次都访问 DOM。

只是提醒一下,像这样的 JavaScript 应该放置在页面底部的结束 上方,

我建议在全局范围内观看此视频:http://www.watchmecode.net/javascript-scope

Here is a solution that will keep only a single object/namespace in the global scope:

(function(global, d) {
    var output = d.getElementById('output'),
        myApi = {};

    myApi.insert_number = function(number){
      output.value += number.value;
    };

    //export your api to the global scope
    global.myApi = myApi;
})(window, document);

Now you can call myApi.insert_number(5); You now have a closure that has access to the output variable so you can add additional functionality to your API without having to access the DOM each time.

Just a reminder, JavaScript like this should be placed at the bottom of your page just above the closing </body>

I would reccomend watching this video on global scope: http://www.watchmecode.net/javascript-scope

在风中等你 2025-01-08 15:27:47

DOM 元素存在,它们都可以工作

document.getElementById('output')

实际上,只要代码运行时 。重要的区别在于,您的 insert_number 函数可能在加载 DOM 之后运行,这与第二个示例中的裸输出分配不同。

另外我如何在函数中编写output变量
insert_number() 同时仍然使输出全局可用
我的脚本中还有其他函数吗?

优秀的 JavaScript 开发人员会尽量避免不必要的全局变量,但简单的答案是:

var output; // declared, but as yet undefined

window.onload = function () {
    window.output = document.getElementById("output");
}

function insert_number(number) {
    output.value += number.value;
}

Actually, they both work, as long as the DOM element at

document.getElementById('output')

exists when the code is run. The important difference is that your insert_number function probably runs after the DOM is loaded, unlike the bare output assignment in the second example.

Also how would I write the output variable within the function
insert_number() while still making output globally available to all
other functions in my script?

Good JavaScript developers try to avoid global variables where unnecessary, but the simple answer is this:

var output; // declared, but as yet undefined

window.onload = function () {
    window.output = document.getElementById("output");
}

function insert_number(number) {
    output.value += number.value;
}
习ぎ惯性依靠 2025-01-08 15:27:47

这与全局变量无关。

您的 head 中可能有该脚本。在此阶段,DOM 尚未完全构建,并且 ID 为 output 的元素还不存在。因此 document.getElementById('output') 将返回 null示例)。

但是,如果您可能在 DOM 构建后的某个时间调用 insert_number,作为对某些用户交互的响应。在这种情况下,该元素将存在。

最简单的解决方案是将代码放在结束 body 标记之前(示例,注意不同的 jsfiddle 设置和/或检查源代码)。

This has nothing to do with global variables.

You are probably having the script inside your head. At that stage, the DOM is not fully built yet and the element with ID output does not exist yet. Hence document.getElementById('output') will return null (example).

But if you are probably calling insert_number some time after the DOM was built, as response to some user interaction. In that case the element will exist.

The simplest solution would be to put your code before the closing body tag (example, notice the different jsfiddle settings and/or inspect the source).

倾城°AllureLove 2025-01-08 15:27:47

我认为你的代码不起作用的原因是因为当你调用 var output = document.getElementById('output'); 时,DOM 没有加载

,将代码移到输出 div 所在的位置下面,它应该工作

I think the reason your code is not working is because the DOM is not loaded when you call var output = document.getElementById('output');

Move the code below where the output div is and it should work

独留℉清风醉 2025-01-08 15:27:47

如果您声明一个变量而不使用“var”,则该变量始终变为全局。更多信息请参见:http://www.w3schools.com/js/js_variables.asp

If you declare a variable, without using "var", the variable always becomes global. More info here: http://www.w3schools.com/js/js_variables.asp

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文