为什么我的回调函数接收未定义的参数值?

Why does my callback function receive undefined as a parameter value?

我正在尝试使用外观非常酷的 Bootstrap Notify 插件,尽管它需要大量 DIY 样式,但效果非常好。

除此之外,插件的主要方法 $.notify(message, options & settings)OnClose 回调提供了一个设置 属性,当通知弹出窗口(toast)关闭时,可以自然关闭,也可以通过单击它的Dismiss 图标。

插件中的代码像这样调用回调:

if ($.isFunction(self.settings.onClose)) {
    self.settings.onClose.call(this.$ele);
}

在它的 close 函数中,当用户解除警报时,或者当它的延迟时间过去并且它自动关闭时调用它。当我在传递给回调调用之前检查 this.$ele 值时,我看到它是一个类似于 jQuery 的对象,表示一个元素的数组,即警报元素正忙于从我的 [=36= 中删除自身]. E.i。包含此元素的数组:

<div data-notify="container" class="col-xs-11 col-sm-4 alert alert-minimalist animated fadeInDown fadeOutUp" role="alert" data-notify-position="top-right" data-closing="true" style="display: inline-block; margin: 0px auto; position: fixed; transition: all 0.5s ease-in-out; z-index: 1031; top: 20px; right: 20px;">
    <button type="button" aria-hidden="true" class="close" data-notify="dismiss" style="position: absolute; right: 10px; top: 5px; z-index: 1033;">×</button>
    <span data-notify="icon"></span>
    <span data-notify="title">
    </span> <span data-notify="message">Hey hey hey!</span><a href="#" target="_blank" data-notify="url"></a>
</div>

我在一个非常简单的测试页面中使用通知插件,像这样:

$("button").click(function () {
    $.notify("Hey hey hey!", {
        type: "minimalist",
        delay: 50000,
        onClose: function(element) {
            console.log("Element: " + element);
        }
    });
});

然而,当调用此 onClose 回调时,其 element 参数值为 undefined。为什么这个值在调用回调和执行回调代码之间变得未定义?

插件中的代码:

self.settings.onClose.call(this.$ele);

不向 onClose() 回调传递任何参数。 .call() 的第一个参数是应该为回调设置的 this 指针。 .call() 的任何后续参数将是回调的实际参数。由于有 none,您要查找的任何内容都将是 undefined

有关详细信息,请参阅 MDN doc for .call()

因此,如果您想访问与此调用关联的元素,则可以在回调中使用 this

$("button").click(function () {
    $.notify("Hey hey hey!", {
        type: "minimalist",
        delay: 50000,
        onClose: function() {
            console.log(this);
        }
    });
});