javascript 访问函数范围外的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16942043/
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
Access variable outside function scope
提问by user2232681
This is a simplified version of what I am trying to accomplish, but I want to pass a variable outside the scope of the function. I am declaring the variable outside the function but can't get it.
这是我试图完成的简化版本,但我想在函数范围之外传递一个变量。我在函数外声明了变量,但无法得到它。
HTML:
HTML:
<p>5</p>
<p>6</p>
<p>7</p>
JS:
JS:
$(document).ready(function () {
var gsd = "";
$("p").each(function () {
if ($(this).text() === "5") {
var gsd = $(this).text();
alert(gsd); // this works
}
})
alert("get var outside func" + gsd); //does not work
});
回答by Igor
You redeclare gsd
as a new variable inside your function. Remove var
in front of gsd
inside the function to address the gsd
in the outer scope.
您gsd
在函数中重新声明为新变量。删除函数内部的var
前面gsd
以解决gsd
外部作用域中的问题。