如果当前页面的 URL 与条目数组匹配,则应执行 if 语句上部的代码,否则将执行下部 (else
) 内的代码:
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上部 if 内的代码无论如何都会运行(带有 top:124px
的 div 显示)。
我做错了什么?
我从这个问题中获取了代码:javascript If statement, looking through an array
最佳答案
使用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>')
}
}
关于javascript - 循环遍历数组的 if 语句不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29464978/