2012-03-05 31 views
2

目前的問題是我改變了從awnser得到的功能,但之前的功能無效。獲取未禁用的下一個對象ID

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) 

回答

1

以下邏輯非常簡單。訣竅是繼續迭代,直到找到一個未禁用的模式,使用模數(%)執行循環操作,直到達到最終結果。

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]; 
} 

只要確保有至少一個啓用了或此將無限循環。 :)

+1

謝謝,我設法調整它一點點,所以它給了我想要的輸出:D你是我的英雄! – 2012-03-05 20:12:39

+0

您可以將功能添加到相冊的任何實例以支持多個相冊:例如, 'album.getNext = getNext'。如果你希望它是一個完全孤立的函數,你需要傳入當前的索引和一個對專輯的引用來迭代,否則它將無法確定下一個/前一個是否被禁用。在這種情況下,一個'album'參數,並將body中'this.album'的每個實例更改爲'album',並且'currPhotoId'也一樣。 – devios1 2012-03-05 20:18:01

1
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 
} 

,如果你想跳過這個元素,並搜索下一個沒有-disabled one

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++; 
} 
+0

對不起,它有點快,我不知道你是否希望我通過它說話嗎?你可以換一個if/else語句的繼續,但這本身應該工作 – outrunthewolf 2012-03-05 19:52:56

+0

是的,我可以使用一些額外的幫助。它也必須從currentID開始吧? – 2012-03-05 19:53:28

+0

我不好,我以爲你想迭代。我會再看一次。我想你可能會過於複雜,你的第一個功能雖然 – outrunthewolf 2012-03-05 19:56:00