当我尝试参加活动时,我得到了:
未捕获的TypeError:无法读取未定义的属性“type”
我正在尝试将options
中的Constructor Itoggle
传递给mouseInOut
,然后将options
传递到Itoggle.prototype.mouseInOut
。在我尝试将任何参数传递给mouseInOut
之前,代码工作正常,现在我再也无法获得event
。即使我尝试传递event
作为参数或任何参数。
错误:
未捕获的TypeError:无法读取undefined makeup-itoggle.js的属性'type':18 Itoggle.mouseInOut makeup-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);
答案 0 :(得分: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
的实例。