我在这里找到了一些用于触摸设备的 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/