这是我的jsfiddle的链接
一个简单的jquery插件
在 147 行的小提琴中,当我尝试执行console.log(this)
时,它给窗口对象而不是在第 166 行的函数调用中传递的元素,$('#loadImage').loadImage()
IDloadImage
。它导致在整个窗口上绑定单击事件处理程序,但不在元素上绑定。这意味着当我单击页面时,事件就会触发。所以我的问题是为什么我无法访问第 147 行的元素但窗口对象。任何帮助将不胜感激。
将处理程序绑定到 DOM 事件时,将在window
上下文中调用处理程序。这是 DOM 事件处理的工作方式。如果要访问单击的对象,只需查看事件对象,请在其中查找target
属性。这是单击的 DOM 元素。因此,在这种情况下,您的点击处理程序将如下所示:
$(this).on('click',function(event){
$('#image_modal').css('display','block');
// event.preventDefault();
event.stopPropagation();
console.log($(event.target));
//$('#image_modal').css('height','100vh');
//return false;
});
控制台日志应指向单击的元素。
更新
插件构造函数(第 141 行(内部this
window
对象的原因是您在第 130 行中使用箭头函数来定义插件。请改用声明性函数定义:
// Adding function // Removed =>
$.fn.loadImage = function (options = null, callback = null) {
if (options !== null) {
// loadImage.settings = $.extend(loadImage.settings, options);
loadImage.updateSettings(options);
}
loadImage.init();
|| // this points to element calling loadImage
||
/
$(this).on('click', function(event) {
$('#image_modal').css('display', 'block');
// event.preventDefault();
event.stopPropagation();
console.log(this);
//$('#image_modal').css('height','100vh');
//return false;
});
$('#modal_close').on('click', function(event) {
$('#image_modal').css('display', 'none');
//$('#image_modal').css('height','0px');
return false;
});
};