【问题标题】:Variable keeps its old value after exit jquery function退出jquery函数后变量保持其旧值
【发布时间】:2013-05-25 17:19:00
【问题描述】:

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

<!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>

【问题讨论】:

标签: jquery function variables exit default-value


【解决方案1】:

这是设计使然,当变量退出内部范围(您的 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/

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      • 1970-01-01
      • 2020-05-14
      相关资源
      最近更新 更多