如何在 jQuery 中的变量中调用函数赋值
how to call function assign in a variable in jquery
我声明了一个函数并将其分配给一个变量,函数内部是其他函数。通常,在第一次加载页面时,它会加载函数等。当我在 ajax 成功回调中使用变量时,它说 init()
函数不是函数。
这是我分配给一个名为 GRID
的变量的示例 jquery 函数:
var Grid = (function() {
function init( config ) { ... }
.
.
.
function addItems( $items ) { ... }
return { init: init, . . . addItems: addItems }
}
();
我有一个这个阿贾克斯电话
function updateItems{
.
.
.
.
jQuery.ajax({
type: 'get',
url: ajaxURL,
data: ajaxData,
dataType: 'json',
//Ajax call is successful
success: function ( response ) {
//Add new posts
Grid.init();
},
error: function () {
}
});
.
.
.
}
代码有什么问题? 为什么检查器会返回一个错误,说 Grid.init() 不是函数? 请帮忙
var Grid = (function() {
function init( config ) { ... }
.
.
.
function addItems( $items ) { ... }
// explicitly return the functions, or properties you want to be attached to `Grid`
return {
init: init,
.
.
.
addItems: addItems
}
// assuming you want this to be immediately invoked function expression
})();
你在 iife 的作用域内定义了 init,但不要将其添加为 Grid 的函数。
你应该做
Grid.init = function(){}
试试这样
var Grid = {
init : function( config ) { ... }
.
.
.
addItems : function( $items ) { ... }
}
您应该将 init 定义为 Grid 中的属性,该属性的值是函数的返回,希望它有所帮助
我试图在那里复制你的案例:JSFiddle
网格 :
var Grid = (function() {
function init(config) {
console.log('--- INIT')
}
function addItems($items) {
console.log('--- ADD ITEMS')
}
return { init: init, addItems: addItems };
})();
然后带有 Ajax 调用的函数:
function updateItems() {
jQuery.ajax({
type: 'get',
url: ajaxURL,
dataType: 'json',
success: function(response) {
Grid.init();
Grid.addItems();
}
});
}
我称这个函数为:
updateItems();
对我来说一切都很好。控制台输出:
---初始化
---添加项目
你能发现你的代码有什么不同吗?
您确定Grid
是全局的还是与updateItems
在同一范围内?
相关文章:
- 如何从模块链中调用函数.导出到节点中
- 调用函数内部的函数
- 在javascript中调用c函数
- DropDownListFor赢得't在更改时调用函数
- Javascript页面调用函数
- 在动画结束之前调用函数
- 允许父窗口在其不同域的子iframe上调用函数
- 运行Infinite Scroll后调用函数时出现问题
- JavaScript:在调用函数的文本输入上按enter键
- 使用大括号和不使用bracs调用函数的区别
- javascript在事件上调用函数
- 从index.html调用函数,该函数无限循环
- 从带参数的字符串变量调用函数中的函数
- 为什么 JS 不在滚动时调用函数
- 是否可以在不更改上下文的情况下调用函数.apply
- 如何在ES6类中使用参数调用函数
- AngularJS:调用函数时编号不更新
- JavaScript中的立即调用函数表达式(IIFE)-传递jQuery
- 在JavaScript中调用函数时自定义此选项
- 调用函数中声明的变量