javascript 如何在函数内部调用函数

标签 javascript

我有以下 JavaScript

(function (document, window, $) {
    'use strict';

    var Site = window.Site;

    $(document).ready(function ($) {
        Site.run();
        var $this = this;

        // Init function
        // ------------------------
        (function () {

            function init() {

                $('tr[data-toggle="slidePanel"]').click(function (e) {
                    e.preventDefault();
                    var me = $(this);

                .... some code here
            }

            init();

        })();

        // Employee function
        // ------------------------
        (function () {

            function getData() {

                ... some code here

                // here is the problem... how can I call buildTable
                $this.buildTable(data);

                ... some code here
                I want to call also the init function on the top.
            }

            function buildTable(data) {

                $('#contactsContent').html(data);

            }   
            getData();
        })();
    });

})(document, window, jQuery);

Employee 主函数内部,我在调用 getData() 函数 buildTable() 时遇到问题,之后我想调用顶部的 init() 函数。

有什么线索吗?

最佳答案

getData()buildTable() 彼此是同级函数,因此它们位于同一范围内。无需在调用前添加 $this 前缀。

只需使用:buildTable(data);

我还必须说,您似乎有很多不必要的函数包装器,将其删除后,也可以直接调用 init()

看起来您还想调用 init() 两次。是这样吗?

最后,如果您确实只有此处显示的代码,则无需使用最外层函数包装所有代码,因为 JQuery document.ready 函数将执行为一旦 DOM 准备好。

这是代码的重写版本:

$(function() {
 'use strict';
   
  var Site = window.Site;
  Site.run();

  // Init function
  (function init() {              
    $('tr[data-toggle="slidePanel"]').click(function (e) {
       e.preventDefault();
       var me = $(this);
       //.... some code here
    }
  })();
        
  // Employee function
  //... some code here
    
  buildTable(data);
    
  //... some code here
  init();
    
  function buildTable(data) {
    $('#contactsContent').html(data);    
  }   
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript 如何在函数内部调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44747840/

相关文章:

javascript - 语法错误: missing: after property id

javascript - XHR 失败时的回退,在 XHR 功能之外

javascript - 在 v-navigation-drawer 关闭的情况下加载网站

javascript - 使用未知长度字符串拆分 JavaScript 字符串,例如\n

javascript - 如何在移动浏览器中隐藏滚动条?

javascript - React 钩子(Hook)需要返回一个值吗?

javascript - jquery - 根据文本输入改变图像

javascript - 如何更改 jquery .toggle() 以使用显示 :table-cell?

javascript - Angular JS - 添加一个 jquery 插件到 jQlite

javascript - 如何在 javascript 或 jquery 中创建动态二维数组?