【问题标题】:Cannot read function of undefined无法读取未定义的函数
【发布时间】:2018-08-24 14:57:01
【问题描述】:

我正在尝试创建另一种扩展 $.event.special 对象的事件类型。因为我需要更改与输入类型不同的元素。问题是当我启动页面时控制台给了我这个错误:

main.js:5 Uncaught TypeError: Cannot read property 'mutationsLists' of undefined

脚本是这样的:

(function($){

 $.event.special.changeElement = {
    eventType: 'changeElement',
    mutationObserver : new MutationObserver($.event.special.changeElement.mutationsLists),

    setup: function(data, namespaces) {
      var config = { attributes: true, childList: true };
      $.event.special.changeElement.mutationObserver.observe(this, config);
    },

    teardown: function(namespaces) {
      $.event.special.changeElement.mutationObserver.disconnect();
    },

    handler: function(event) {
      event.type = $.event.special.changeElement.eventType;
      return $.event.dispatch.apply(this, arguments);
    },

    mutationsLists : function(mutationsList) {
      for(var mutation of mutationsList) {
          if (mutation.type == 'childList') {
              console.log('A child node has been added or removed.');
          }
          else if (mutation.type == 'attributes') {
              console.log('The ' + mutation.attributeName + ' attribute was modified.');
          }
      }
    }

  }

})(jQuery);

我检查了一下,它看起来 $.event.special.changeElement 已定义,但在调用其成员时看起来未定义...

【问题讨论】:

    标签: jquery function events plugins undefined


    【解决方案1】:

    mutationLists$.event.special.changeElement 的一个属性,它是一个函数。将属性作为对象的函数充当函数表达式,这意味着在到达代码之前未定义。有关这方面的示例,请参阅此jsFiddle

    您会在那个小提琴中看到firstFunction 可以调用secondFunction,因为它是在它之前定义的。但是,secondFunction 不能调用 thirdFunction,因为它在调用 firstFunction 之前没有定义。

    要纠正您的问题,请先定义函数 mutationLists,然后再定义属性 mutationObserver

    【讨论】:

    • 这个我也试过了,还是不行。唯一有效的方法是将mutationList 作为外部函数调用。
    • 由于你在对象的同一范围内访问函数的引用,你应该使用'this'关键字。例如 this.mutationLists
    • 我也做了这个......当我制作这个的console.log时,我看到这是一个窗口对象......
    • 为什么需要在对象中创建 MutationObserver 的实例?正如你所提到的,为什么你不能在对象被定义之后实例化它?
    • 哦,好的。但是我怎样才能得到启动它的句柄???我尝试使用 $._data(this, "events") 但如何获得通过 $(...).on('changeElement', f....) 传递的句柄?我需要在dom突变后启动f...
    猜你喜欢
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 2018-10-30
    • 2018-04-01
    • 2020-03-26
    • 2018-09-13
    相关资源
    最近更新 更多