jQuery if语句破坏了我的代码

Eva*_*nss 1 javascript jquery if-statement

这是我的代码:

$("#header").touchwipe({
//  if($('#cont-wide').css('left') == '-100%' ){
         wipeLeft: function() { 

                $('#cont-wide').animate({
                        left: '-201%'
                }, 500 );
                $('#nav-filters').fadeOut(200);
                $('#nav-map-l').delay(300).fadeIn(200);

                $('#one .col-inner').delay(500).hide(0);

                $('#three .col-inner').css('display','block');

                setTimeout(function() { 
                window.scrollTo(0, 1) }, 
                100);
            },
         wipeRight: function() { 

                $('#cont-wide').animate({
                        left: '1%'
                }, 500 );
                $('#nav-filters').fadeOut(200);
                $('#nav-map-r').delay(300).fadeIn(200);

                $('#one .col-inner').css('display','block');

                setTimeout(function() { 
                window.scrollTo(0, 1) }, 
                100);

            },
         min_move_x: 50,
         min_move_y: 50,
         preventDefaultEvents: false
//  }   
});
Run Code Online (Sandbox Code Playgroud)

因为它目前是正常的.但是,当我删除注释以添加条件语句时,代码和我所有其他JavaScript都停止工作.谢谢

Man*_*eUK 7

你不能把if声明放在那里......

你可以这样做:

 wipeLeft: function() { 
      if($('#cont-wide').css('left') == '-100%' ){
         // the rest
      }
 },
 wipeRight: function() { 
      if($('#cont-wide').css('left') == '-100%' ){
         // the rest
      }
 }
Run Code Online (Sandbox Code Playgroud)

注意 - css我的函数不会产生你期望的结果:http://jsfiddle.net/VccAn/在我的示例中使用10%for 值left返回autoChrome!有关此问题的讨论,请参阅此问题/答案:jQuery .css("left")在Chrome中返回"auto"而不是实际值


Thi*_*ter 5

你不能只是在if声明中间发表声明.

最好的解决方案是在调用之前创建选项对象touchwipe():

var options = {};
if($('#cont-wide').css('left') == '-100%') {
    options.wipeLeft = function() {

    };

    options.wipeRight = function() {

    };
}

$("#header").touchwipe(options);
Run Code Online (Sandbox Code Playgroud)

请注意,if条件仅评估一次.如果你想在每个事件上评估它,@ ManseUK的答案是要走的路.