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

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

Access variable outside function scope

javascriptfunctionvariablesscope

提问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 gsdas a new variable inside your function. Remove varin front of gsdinside the function to address the gsdin the outer scope.

gsd在函数中重新声明为新变量。删除函数内部的var前面gsd以解决gsd外部作用域中的问题。