我有以下 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/