【问题标题】:swipe-function does not work with my if-statement刷卡功能不适用于我的 if 语句
【发布时间】:2013-10-31 15:36:50
【问题描述】:
(function(){
    if ($('#right-col').hasClass('shown')){
        $(this).swipe({
            swipe:function(event, direction, distance, duration, fingerCount) {
                $(this).addClass('hidden');//.text(direction);
            }
        });
    }; 
})();

这是我正在处理的网络项目的滑动功能。但不知何故,我的代码不适用于 if 语句。如果我只使用这个:

$('#right-col').swipe({
  swipe:function(event, direction, distance, duration, fingerCount) {
    $(this).addClass('bg-blue').text("You swiped " + direction );
  }
})

它工作正常。谁能告诉我,我上面的自调用功能有什么特别错误的吗?

【问题讨论】:

  • (this) 不会在这样的 if 语句中触发

标签: javascript jquery mobile swipe


【解决方案1】:

当您执行$(this).swipe(...) 时,this 就是window。使用其 id 选择元素:

(function () {
    if ($('#right-col').hasClass('shown')) {
        $('#right-col').swipe({
            swipe: function (event, direction, distance, duration, fingerCount) {
                $(this).addClass('hidden'); //.text(direction);
            }
        });
    };
})();

请注意,如果稍后#right-col 元素的类发生变化,则滑动功能不会受到影响。

【讨论】:

  • 是的,这解决了我的问题。有时我仍然使用错误的“this”关键字。不过谢谢你的帮助!
  • this 在 javascript 中肯定会令人困惑。
【解决方案2】:

这有点跑题了……但前段时间我写了自己的滑动功能。

这个功能主要在ios设备上测试。

1.创建自定义事件。

fc = 快速点击

swl = 向左滑动

swr = 向右滑动

swu = 向上滑动

swd = 向下滑动

2.它比其他滑动要快得多,您可以使用简单的纯js addeventlistener 或attachevent。

3.它是用纯javascript编写的。

4.fastclick 事件也可以让你更快地点击元素..

点击 = 400-500ms

快速点击 = 40-50 毫秒

window.onload=function(){
(function(d){
 var
 ce=function(e,n){var a=document.createEvent("CustomEvent");a.initCustomEvent(n,true,true,e.target);e.target.dispatchEvent(a);a=null;return false},
 nm=true,sp={x:0,y:0},ep={x:0,y:0},
 touch={
  touchstart:function(e){sp={x:e.touches[0].pageX,y:e.touches[0].pageY}},
  touchmove:function(e){nm=false;ep={x:e.touches[0].pageX,y:e.touches[0].pageY}},
  touchend:function(e){if(nm){ce(e,'fc')}else{var x=ep.x-sp.x,xr=Math.abs(x),y=ep.y-sp.y,yr=Math.abs(y);if(Math.max(xr,yr)>20){ce(e,(xr>yr?(x<0?'swl':'swr'):(y<0?'swu':'swd')))}};nm=true},
  touchcancel:function(e){nm=false}
 };
 for(var a in touch){d.addEventListener(a,touch[a],false);}
})(document);

// example
var h=function(e){console.log(e.type);};
document.body.addEventListener('fc',h,false);
document.body.addEventListener('swl',h,false);
document.body.addEventListener('swr',h,false);
document.body.addEventListener('swu',h,false);
document.body.addEventListener('swd',h,false);

}

这里有更多关于如何使用它的细节..

https://stackoverflow.com/a/17567696/2450730

它可能也适用于 android。

【讨论】:

    猜你喜欢
    • 2021-08-26
    • 1970-01-01
    • 2023-01-15
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 2018-08-23
    • 1970-01-01
    相关资源
    最近更新 更多