javascript - 将 "this"传递给自定义 Tap 事件回调的正确方法

标签 javascript jquery touch this tap

我在这里找到了一些用于触摸设备的 JavaScript 点击事件的代码:GitHub page归功于Jørn Kinderås对于此代码。

我的问题是,如果我做这样的事情: $('.支持输入').tap(function () { $(this).click(); });

它不起作用,因为 this 引用了 DOMWindow (正如我通过执行 console.log(this) 可以看到的那样。

我目前找到的解决方法是更改​​点击事件代码中的几行。我更改了以下内容:

elem.on('touchend', _bind(function (e) {
    endTime = new Date().getTime();
    if (!didMove && ((endTime - startTime) < tapCancelTime)) {
        callback(e);
    }
}, this));

对此:

elem.on('touchend', _bind(function (e) {
    endTime = new Date().getTime();
    if (!didMove && ((endTime - startTime) < tapCancelTime)) {
        elem.onTap = callback;
        elem.onTap(e);
    }
}, this));

我觉得可能有更好的方法来做到这一点,因为整个 elem.onTap = callback; 感觉很脏。

这是来自 GitHub 的源代码:

(function ($) {
    "use strict"
    $.fn.tap = function (callback) {
        var version, didMove, tapCancelTime, startTime, endTime, _bind;
        version = "1.0.1";
        tapCancelTime = 2 * 1000;
        _bind = function (fn, me) { return function () { return fn.apply(me, arguments); }; };

        return this.each(
            function (index, element) {
                var elem = $(element);

                elem.on('click', function (e) {
                    e.preventDefault();
                });

                elem.on('touchstart', _bind(function (e) {
                    didMove = false;
                    startTime = new Date().getTime();
                }, this));
                elem.on('touchmove', _bind(function (e) {
                    didMove = true;
                }, this));
                elem.on('touchend', _bind(function (e) {
                    endTime = new Date().getTime();
                    if (!didMove && ((endTime - startTime) < tapCancelTime)) {
            callback(e);
                    }
                }, this));
                elem.on('touchcancel', _bind(function (e) {
                    callback(e);
                }, this));
            }
        );
    };
})(jQuery);

最佳答案

使用 .apply().call()this 的所需值传递给任何函数。

根据您的情况,您可以更改此设置:

callback(e);

对此:

callback.call(this, e);

或者这个(可能适合你的情况):

callback.call(elem, e);

然后回调函数将获得事件处理程序中的 this 值,而不是 window。仅供引用,当您知道要传递给方法/函数的所有参数时,您可以使用 .call() 。当您有类似数组的参数数据结构并且想要传递数组中的所有参数时,可以使用 .apply()

有关引用,请参阅MDN有关 .call().apply() 的更多信息。

关于javascript - 将 "this"传递给自定义 Tap 事件回调的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16323566/

相关文章:

javascript - 带有文件 uploader 解决方案的联系表

javascript - jQuery 从一个 div 中选择每个元素并粘贴到另一个元素中

javascript - 如何使用 Ajax 和 jQuery 传递两个不同选择标签的值以进行处理?

javascript - 如何在 React js 中设置全局字体系列?

javascript - ajax帖子隐藏按钮

javascript - Jquery 将 div 中的文本拖放到较小的 div 中

android - 如何制作特殊区域以调用触摸事件?

java - 如何保持 Canvas 的某些部分不可触摸

java - LibGDX 游戏 : Check if button is touched when touchDown is called