2014-11-05 41 views
0

我有以下代碼,它位於滑動功能內。變量爲空時仍在運行的條件

當檢測到滑動時,將運行此代碼。

在頂部,您會看到我正在檢查是否存在以前幻燈片的ID。如果這返回爲'未定義',我將變量設置爲null

然後,在'左'或'右'條件下,我檢查prevIdnextId是否有值。例如:if (direction == "left" && nextId) {

我已檢查過,值爲null,但條件仍然存在。我嘗試了幾種不同的組合,但每次值都爲空並且仍然運行。

有沒有人有任何想法?

var prevId = $('.active').prev('.slide-item').attr('id'); 
var nextId = $('.active').next('.slide-item').attr('id'); 

if (prevId === undefined) { 
    prevId = null; 
} 
if (nextId === undefined) { 
    nextId = null; 
} 

if(phase == "move" && (direction == "left" || direction == "right")) { 

    var duration = 0; 
    if (direction == "left" && nextId) { 
     scrollImages(0 - distance, duration); 
    } else if (direction == "right" && prevId) { 
     scrollImages(0 + distance, duration); 
    } 
} else if (phase == "cancel") { 
    $('.active').css("-webkit-transform", "translate3d(0px,0px,0px)") 
       .css("-moz-transform", "translate3d(0px,0px,0px)") 
       .css("-ms-transform", "translate3d(0px,0px,0px)") 
       .css("-0-transform", "translate3d(0px,0px,0px)") 
       .css("transform", "translate3d(0px,0px,0px)"); 
} else if (phase =="end") { 
    if (direction == "right") { 
     prev(); 
    } else if (direction == "left") { 
     next(); 
    } 
} 

回答

0

試試下面的代碼

var prevId = $('.active').prev('.slide-item').attr('id'); 
var nextId = $('.active').next('.slide-item').attr('id'); 

if (prevId === undefined) { 
    prevId = null; 
} 
if (nextId === undefined) { 
    nextId = null; 
} 

if(phase == "move" && (direction == "left" || direction == "right")) { 

    var duration = 0; 
    if (direction == "left" && !nextId) { 
     scrollImages(0 - distance, duration); 
    } else if (direction == "right" && !prevId) { 
     scrollImages(0 + distance, duration); 
    } 
} else if (phase == "cancel") { 
    $('.active').css("-webkit-transform", "translate3d(0px,0px,0px)") 
       .css("-moz-transform", "translate3d(0px,0px,0px)") 
       .css("-ms-transform", "translate3d(0px,0px,0px)") 
       .css("-0-transform", "translate3d(0px,0px,0px)") 
       .css("transform", "translate3d(0px,0px,0px)"); 
} else if (phase =="end") { 
    if (direction == "right") { 
     prev(); 
    } else if (direction == "left") { 
     next(); 
    } 
} 
+0

感謝PROG,但仍沒有運氣。變量是'null',它仍然運行條件。 – ccdavies 2014-11-05 11:17:14

+0

您是否使用過'if(direction ==「left」&&!nextId){...}'? – prog1011 2014-11-05 11:18:37

+0

看到相同的問題 - http://stackoverflow.com/questions/6003884/how-do-i-check-for-null-values-in-javascript – prog1011 2014-11-05 11:22:25