退出jquery函数后,变量保持其旧值

时间:2013-05-30 08:06:34

标签: jquery function variables exit default-value

我有一个简单的函数可以更改传递给它的变量。但退出函数后,变量返回旧值。我不知道为什么或如何解决它

<!DOCTYPE html>
<html>
<head>

  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>    

  <script>
    $(document).ready(function() {
        var a='test';

        $().doit(a);
        alert(a);
    });

    (function ($) {
            $.fn.doit = function (input) {
                alert(input);
                input='new';
                alert(input);
            };

    }(jQuery));
  </script>
</head>

<body>
</body>
</html>

2 个答案:

答案 0 :(得分:4)

这是设计的,当变量退出内部作用域(你的doit函数)时,值会回到之前的值,因为在JS中变量总是按值传递。

如果您想保留该值,则必须从函数中返回值:

<script>

    $(document).ready(function() {
        var a='test';

        a = $().doit(a);
        alert(a);
    });

    (function ($) {
            $.fn.doit = function (input) {
                alert(input);
                input='new';
                alert(input);
                return input;
            };

    }(jQuery));
  </script>

您可以在此处看到它:http://jsfiddle.net/nQSNy/

答案 1 :(得分:1)

这是因为您按值而不是通过引用传递变量a。但是,您可以从函数中返回一个值并使用它。

相关问题