获取未禁用的下一个对象ID

时间:2012-03-05 19:47:35

标签: javascript object

现在的问题是我改变了我从答案中得到的功能,但前一个功能不起作用。

function getPrev(currPhotoId) {
    var i = currPhotoId - 1;
    i %= album.length;
    while ( album[i].disabled ) {
        i--;
        i %= album.length;
    }
    return i;
}

输出的工作时间长于0

TypeError: album[i] is undefined
undefined = "0"   
while ( album[i].disabled ) 

2 个答案:

答案 0 :(得分:0)

function removeImage(element, event){
    var albumHolder = document.getElementById('album');
    albumHolder.removeChild(element);
    event.preventDefault();
    currPhotoId = element.id.split("_");

    // This should be a bit simpler
    album[currPhotoId].disabled = true;
    console.log(album);
}

...然后

function disabledCheck(currentID, direction)
if(album[currentID].disabled){
    // search for next one which isn't disabled in next or previous direction
}else{
    return currentID
}

如果您想跳过此元素并搜索下一个未禁用的元素

function disabledCheck(currentID, direction)
for(var i = 0; i < (album.length - currentID))
{
    if(album[currentID].disabled){
        // search for next one which isn't disabled in next or previous direction
        continue;
    }else{
        return currentID
    }
    i++;
}

答案 1 :(得分:0)

以下逻辑非常简单。诀窍是继续迭代,直到找到一个未被禁用的方法,使用模数(%)在你到达终点时执行循环。

function getNext() {
    var i = this.currPhotoId + 1;
    i %= this.album.length;
    while ( this.album[i].disabled ) {
        i++;
        i %= this.album.length;
    }
    return this.album[i];
}

function getPrev() {
    var i = this.currPhotoId - 1;
    i %= this.album.length;
    while ( this.album[i].disabled ) {
        i--;
        i %= this.album.length;
    }
    return this.album[i];
}

确保至少有一个启用了 ,否则这将无限循环。 :)