2015-04-06 69 views
0

如果當前頁面的URL與條目數組相匹配,if語句上部的代碼應該執行,否則底部(else)內的代碼將執行:If語句循環顯示陣列不工作

window.onload = function() { 
    var currentPage = [ 
    'http://www.chineselearnonline.com/amember/member.php', 
    'http://www.chineselearnonline.com/amember/profile.php' 
    ] 

    if (currentPage.indexOf(2) == -1) { 
    document.getElementsByClassName('grey-block')[0] 
     .insertAdjacentHTML('afterend', '<div style="top:124px;" class="orange-block-2"><a href="http://clo2015.chineselearnonline.com/">Try out the New Version of CLO</a></div>') 
    } else { 
    document.getElementsByClassName('grey-block')[0] 
     .insertAdjacentHTML('afterend', '<div class="orange-block-2"><a href="http://clo2015.chineselearnonline.com/">Try out the New Version of CLO</a></div>') 
    } 
} 

但是,正如你所看到的:http://www.chineselearnonline.com/nlevel1上面的代碼如果運行無論如何(與top:124px div顯示)。

我在做什麼錯?

我把代碼這樣的問題:javascript If statement, looking through an array

+0

抱歉..你是什麼意思?你的意思是,如果當前頁面的URL匹配的項在數組中,然後你想要if塊執行 – 2015-04-06 03:35:42

+0

@ArunPJohny是的,我會說得更好。 – alexchenco 2015-04-06 03:36:34

+0

由於currentPage數組只有兩個元素,currentPage.indexOf(2)== -1將計算爲true,因此將執行第一個if塊。 – 2015-04-06 03:40:14

回答

2

使用window.location.href檢查,如果您的當前頁面匹配的數組中的任何東西:

window.onload = function() { 
    var currentPage = [ 
     'http://www.chineselearnonline.com/amember/member.php', 
     'http://www.chineselearnonline.com/amember/profile.php' 
    ] 

    if (currentPage.indexOf(window.location.href) == -1) { 
     document.getElementsByClassName('grey-block')[0] 
    .insertAdjacentHTML('afterend', '<div style="top:124px;" class="orange-block-2"><a href="http://clo2015.chineselearnonline.com/">Try out the New Version of CLO</a></div>') 
    } else { 
     document.getElementsByClassName('grey-block')[0] 
    .insertAdjacentHTML('afterend', '<div class="orange-block-2"><a href="http://clo2015.chineselearnonline.com/">Try out the New Version of CLO</a></div>') 
    } 
} 
2

在你的代碼總是檢查數組中的數值2的指數,因爲該值不存在,它總是返回-1所以如果塊始終執行。

由於您要檢查當前頁面的網址,您可以嘗試查看document.URL是否存在於數組中。

window.onload = function() { 
    var currentPage = [ 
     'http://www.chineselearnonline.com/amember/member.php', 
     'http://www.chineselearnonline.com/amember/profile.php'] 

    if (currentPage.indexOf(document.URL) > -1) { 
     document.getElementsByClassName('grey-block')[0].insertAdjacentHTML('afterend', '<div style="top:124px;" class="orange-block-2"><a href="http://clo2015.chineselearnonline.com/">Try out the New Version of CLO</a></div>') 
    } else { 
     document.getElementsByClassName('grey-block')[0].insertAdjacentHTML('afterend', '<div class="orange-block-2"><a href="http://clo2015.chineselearnonline.com/">Try out the New Version of CLO</a></div>') 
    } 
}