【问题标题】:jquery nested function accessjquery嵌套函数访问
【发布时间】:2015-09-24 11:19:38
【问题描述】:

如何在 onclick 中访问 test2() 外部函数,如普通函数所示,用括号括起来告诉运行时将函数返回到父作用域,一旦返回,函数将使用第 4 行执行,也许阅读这些步骤会有所帮助。

<p onclick='test().test2()'> some text </p>; 

<script>

  //the below declaration will not change 
  var jQuery = 'Hi';
  (function ($) { 
    function test(){
      function test2(){
        alert('text')
      }
      alert($)
    } 
    console.log($);
    test().test2()
  })(jQuery)

</script>

【问题讨论】:

  • 一个简单的建议,可以在文档中查找 javascript 基础知识,尤其是 javascript 中的 OOP。

标签: javascript jquery object


【解决方案1】:

只有在您希望访问该函数的范围内声明该函数时,您才能访问test2。在这种情况下,这意味着您需要在外部范围内声明该函数。

您可以通过在外部范围内设置一个变量来做到这一点,如下所示:

var test2;
 var jQuery = 'Hi';
  (function ($) { 
    function test(){
      test2 = function(){
        alert('text')
      }
      alert($)
    } 
    console.log($);
    test(); //test needs to be called first to define test2.
    test2();
  })(jQuery)

【讨论】:

    【解决方案2】:

    我检查了两次,这很有效:

        var jQuery = 'Hi';
        window.test = (function ($) {
            function test(){
                this.test2 = function () {
                    alert('text')
                };
                alert($);
                return this;
            }
            console.log($);
            test().test2();
    
            return test;
        })(jQuery);
    

    【讨论】:

    • 这不是一般问题的最佳解决方案,但此代码有效。
    • 我检查了 Chrome 控制台。我在 Chrome 控制台中执行了代码。然后我将 'onclick='test().test2()' 添加到页面的 'body' 元素中。点击后我有两个警报(“嗨”和“文本”)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 2015-05-19
    相关资源
    最近更新 更多