如何在 jQuery 中的变量中调用函数赋值

how to call function assign in a variable in jquery

本文关键字:调用 函数 赋值 变量 jQuery      更新时间:2023-09-26

我声明了一个函数并将其分配给一个变量,函数内部是其他函数。通常,在第一次加载页面时,它会加载函数等。当我在 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在同一范围内?