gpt4 book ai didi

javascript - 在匿名函数中更改 $(this) 上下文

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:37:20 25 4
gpt4 key购买 nike

这是我用来在移动设备上绑定(bind)“点击”事件的函数。基本正常的功能。

bindTapEvent: function(container, selector, run, bindClickAlso){
var startX, startY, currentX, currentY = 0;
var moved = false;
var self;

if(touchDevice){
container.on({
click: function(e){
e.preventDefault();
},
touchstart: function(e){
e.preventDefault();
self = $(this);
startX = e.originalEvent.touches[0].pageX;
startY = e.originalEvent.touches[0].pageY;
},
touchmove: function(e){
currentX = e.originalEvent.touches[0].pageX;
currentY = e.originalEvent.touches[0].pageY;
if(Math.abs(startX - currentX) > 10 || Math.abs(startY - currentY) > 10){
moved = true;
}
},
touchend: function(e){
e.preventDefault();
run();
}
},
selector
)
} else {
if(bindClickAlso != false){
container.on('click', selector, function(){
run();
});
}
}
}

我这样使用它:

tt.bindTapEvent(container, '.showColumns', function(){
container.find('.column').addClass('visible');
$(this).doSomething();
});

唯一的问题是我不能(显然)在这样的东西中使用 $(this)。我读过有关更改上下文的 jQuery $.proxy 的信息,但我无法理解它,所以我可以使用它。是否有可能(在我的例子中)将 tt.bindTapEvent 中使用的匿名函数的上下文更改为当我使用 $(this) 时它仅在 bindTapEvent 函数中“存储”和“使用”?

最佳答案

看看 .call() 和 .apply(),它们可以让您将所需的上下文作为第一个参数传递。

http://odetocode.com/blogs/scott/archive/2007/07/05/function-apply-and-function-call-in-javascript.aspx

因此在您的示例中,您可以使用 run.call(this); 而不是 run(),因此您将 this 作为回调函数的上下文传递。

关于javascript - 在匿名函数中更改 $(this) 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10922121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com