$(function(){
$(".Pitm").touchwipe({
wipeLeft:function(){ Showdel();},
min_move_x: 20,
min_move_y: 20,
preventDefaultEvents: true
})
})
function Showdel (c){
c.hide();
}
其中 .Pitm 有多个,需要隐藏当前容器
jquery 自定义事件怎样传递 this
答案:3 悬赏:0
解决时间 2021-04-07 11:49
- 提问者网友:我是我
- 2021-04-06 12:46
最佳答案
- 二级知识专家网友:何以畏孤独
- 2021-04-06 13:31
$(function(){
var fun = function (dom) {
var obj = {
wipeLeft: function(){
Showdel(dom);
},
min_move_x: 20,
min_move_y: 20,
preventDefaultEvents: true
};
return obj;
};
$(".Pitm").touchwipe(fun ($(this)));
});
function Showdel (c){
c.hide();
}
var fun = function (dom) {
var obj = {
wipeLeft: function(){
Showdel(dom);
},
min_move_x: 20,
min_move_y: 20,
preventDefaultEvents: true
};
return obj;
};
$(".Pitm").touchwipe(fun ($(this)));
});
function Showdel (c){
c.hide();
}
全部回答
- 1楼网友:而你却相形见绌
- 2021-04-06 15:00
两个地方需要说明
1. $.fn.xxx 中的 this 指向的是 $() 调用时的 jquery 对象,不用再通过$来封装;
2. $.fn.longpress 中,如果要调用参数里的 fn,并且正确传递dom对象的话,需要写成类似以下这样:
$.fn.longpress = function(fn) {
...
this.each(function() {
fn.apply(this );
});
};用 apply 方法来替换回调函数fn中的 this 。
具体来说,在settimeout的时候,可以类似这么调用:
timeout = settimeout(function() {
fn.apply($temthis[i]);
}, 800);这样,在 fn() 中的this就变成当前dom对象了。
但是,这样写还有一个重要问题,那就是变量 i ,它的值在当前闭包环境中会变成 $temthis.length ,导致代码出错。要正确工作,需要改成这样:
for(var i = 0; i < $temthis.length; i++) {
(function(target) {
var timeout;
target.addeventlistener('touchstart', function(event) {
timeout = settimeout(function() {
fn.apply(target);
}, 800);
}, false);
target.addeventlistener('touchend', function(event) {
cleartimeout(timeout);
}, false);
})($temthis[i]);
}这样创建一个闭包,确保$temthis[i]在每个闭包中都是正确的。另外注意那个timeout,由于对象可能有多个,因此每个对象需要一个单独的 timeout 。
使用 jquery 的方法会简化一些,含义是一样的,如下:
$temthis.each(function() {
var timeout, target = this;
this.addeventlistener('touchstart', function(event) {
timeout = settimeout(function() {
fn.apply(target);
}, 800);
}, false);
this.addeventlistener('touchend', function(event) {
cleartimeout(timeout);
}, false);
});
- 2楼网友:闲懒诗人
- 2021-04-06 14:23
定义一个 var that = this ,用that替换子作用域链
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯