0

当我尝试获取事件时,我得到了:

未捕获的类型错误:无法读取未定义的属性“类型”

我正在尝试options通过Constructor ItoggletomouseInOut然后options进入Itoggle.prototype.mouseInOut. 在我尝试将任何参数传递给 之前,代码工作正常mouseInOut,现在我无法再获得event了。即使我也尝试event作为参数传递或任何参数。

错误:

未捕获的类型错误:无法读取未定义化妆-itoggle.js 的属性“类型”:18 Itoggle.mouseInOut 化妆-itoggle.js:18
b.event.special.(匿名函数).handle
b.event.dispatch
v.handle


;(function ($) {

  "use strict"; 

  var Itoggle = function (el, options) {
    $(el).on('mouseenter mouseleave', mouseInOut(event, options);
  };

  Itoggle.prototype.mouseInOut = function (event, options) {
    var $this = $(this)
      , selector = $this.attr('data-target')
      , target = $('#' + selector);

    var opt = $.extend({}, $.fn.itoggle.defaults, options);
    console.log(opt.titleActive); // ok

    if (event.type == 'mouseover') {//here's come the error. Cannot read property 'type' of undefined
      $this.addClass(opt.elementActive);
      $this.find('.nav-button-title').addClass(opt.titleActive);
      target.show();
    } 
    else if (event.type == 'mouseout') {
      $this.removeClass(opt.elementActive);
      $this.find('.nav-button-title').removeClass(opt.titleActive);
      target.hide();

      target.mouseenter( function () {
        $this.addClass(opt.elementActive);
        $this.find('.nav-button-title').addClass(opt.titleActive);
        target.show();
      });

      target.mouseleave( function () {
        $this.removeClass(opt.elementActive);
        $this.find('.nav-button-title').removeClass(opt.titleActive);
        target.hide();
      }); 

   } 
   else { console.log('invalid event'); }



 };

 /* ITOGGLE PLUGIN DEFINITION
  * ========================= */

  $.fn.itoggle = function () {
    return this.each( function () {
      var $this = $(this)
        , data = $this.data('itoggle')
        , options = typeof option == 'object' && option;
      if (!data) { $this.data('itoggle', (data = new Itoggle(this, options)));}
    });
  };

  $.fn.itoggle.defaults = {
    elementActive: 'nav-outer-button-active',
    titleActive: 'nav-button-title-active'
  };

  $.fn.itoggle.Constructor = Itoggle;


})(window.jQuery);
4

1 回答 1

0

您传递函数结果而不是函数:

// wrong, function executes immediately,
// event is undefined atm, so it throws an error
$(el).on('mouseenter mouseleave', mouseInOut(event, options));

// correct way?
$(el).on('mouseenter mouseleave', mouseInOut);

虽然我很惊讶这行得通。通常,您必须传递这样的函数:

$(el).on('mouseenter mouseleave', this.mouseInOut);

但显然,如果它按你的方式工作 - 那我就错了。

请记住,执行上下文将是触发事件的 HTMLElement,而不是Itoggle.

于 2013-03-23T21:27:38.127 回答