当变量为空时,条件仍在运行

时间:2014-11-05 10:41:57

标签: jquery

我有以下代码,它位于滑动功能中。

检测到滑动时,此代码会运行。

在顶部,您会看到我正在检查以前的幻灯片是否有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();
    }
}

1 个答案:

答案 0 :(得分: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();
    }
}