javascript 函数中的jquery变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10032979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:31:00  来源:igfitidea点击:

jquery variable in function

javascriptjqueryvariables

提问by user1022585

On pageload I set a variable

在页面加载时我设置了一个变量

$(document).ready(function() {
  var inv_count = 3;
  });

When I try to refer to that variable inside functions though, it doesn't work.

但是,当我尝试在函数内部引用该变量时,它不起作用。

function blah(a,b) {
   alert (inv_count);
   }

Why is this? And how can I get around it?

为什么是这样?我怎样才能解决它?

(rookie here)

(这里是菜鸟)

回答by nicosantangelo

You have a problem of scope, I suggest you read a little about it because you can improve your javascript a ton, but you could solve it in two general ways:

你有一个scope问题,我建议你阅读一些关于它的内容,因为你可以大量改进你的 javascript,但你可以通过两种一般方式解决它:

var inv_count; //you declare your variable in a global scope, it's not very good practice
$(document).ready(function() {
    inv_count = 3;
});
function blah(a,b) {
   alert (inv_count);
}

or

或者

$(document).ready(function() {
    var inv_count = 3;

    function blah(a,b) {
      alert (inv_count);
    }
    //you declare everything inside the scope of jQuery, if you want to acess blah outside use:
   //window.blah = blah;
});

Also I recommend you read about clousuresif you don't know how they work.

另外,如果您不知道clouses是如何工作的,我建议您阅读有关closures 的内容。

回答by Michael Liu

If you declare a variable inside a function, the variable name will be inaccessible outside the scope of that function. Move the declaration outside the function:

如果在函数内部声明变量,则变量名称在该函数范围之外将无法访问。将声明移到函数外:

var inv_count;
$(document).ready(function() {
    inv_count = 3;
});