繁体   English   中英

如何从javascript函数之外获取价值?

[英]How to get value from outside of the function in javascript?

如何从另一个函数获取var值?

jQuery的

$(document).ready(function() {
    function GetBiggestValue() {
        var value = 0;
        $('#tagCloud li a').each(function() {
            if (value < $(this).attr('value')) {
                value = $(this).attr('value');
            }
        });
        var FullValue = value;
    }

    function Abc(){
        console.log(FullValue);
    }

    Abc();
});

HTML:

<ul id="tagCloud">
    <li><a href="#" value="1">Val 1</a></li>
    <li><a href="#" value="2">Val 2</a></li>
    <li><a href="#" value="3">Val 3</a></li>
    <li><a href="#" value="4">Val 4</a></li>
</ul>

您不能从自己或父上下文之一以外的其他上下文访问变量。 FullValue变量是GetBiggestValue()函数专用的,因为您使用var语句定义了变量。 在您的情况下,正确的过程是从GetBiggestValue()函数返回value (尽管可能会使用GetBiggestValue()外部的变量提出另一种解决方案来存储值)。

$(document).ready(function() {
    function GetBiggestValue() {
        var value = 0;
        $('#tagCloud li a').each(function() {
            if (value < $(this).attr('value')) {
                value = $(this).attr('value');
            }
        });
        return value;
    }

    function Abc(){
        console.log(GetBiggestValue());
    }
    Abc();
});

可能是您想在任何地方使用此值。 因此,调用GetBiggestValue()函数并为其分配一个变量。

function GetBiggestValue() {
    var value = 0;
    $('#tagCloud li a').each(function() {
        if (value < $(this).attr('value')) {
            value = $(this).attr('value');
        }
    });
    return value;
}

var FullValue = GetBiggestValue();

function Abc(){
    console.log(FullValue);
}

只需从GetBiggestValue函数返回值:

function GetBiggestValue() {
    var value = 0;
    $('#tagCloud li a').each(function() {
        if (value < $(this).attr('value')) {
            value = $(this).attr('value');
        }
    });
    return value;
}

function Abc(){
    console.log(GetBiggestValue());
}

在函数外声明

var value = 0;
$(document).ready(function() {
function GetBiggestValue() {
        value = 0;
        $('#tagCloud li a').each(function() {
            if (value < $(this).attr('value')) {
                value = $(this).attr('value');
            }
        });

    }
    function Abc(){
        console.log(value);
    }
    Abc();
});

或返回值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM