访问函数范围外的变量 [英] Access variable outside function scope

查看:96
本文介绍了访问函数范围外的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我试图完成的简化版本,但我想在该函数的范围之外传递一个变量。

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:

<p>5</p>
<p>6</p>
<p>7</p>

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
});


推荐答案

您重新声明 gsd 作为函数内的新变量。在函数内的 gsd 前面删除 var 来解决 gsd 在外部范围内。

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.

这篇关于访问函数范围外的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆