如果循环数组的语句不起作用

时间:2015-04-06 03:34:00

标签: javascript if-statement

如果当前页面的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无论如何都会运行上层内部的代码(显示top:124px的div)。

我做错了什么?

我从这个问题中获取了代码:javascript If statement, looking through an array

2 个答案:

答案 0 :(得分:2)

在你的代码中,你总是检查数组中数值2的索引,因为该值不存在,它将始终返回-1,因此始终执行if块。

由于您要检查当前页面的网址,您可以尝试查看数组中是否存在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>')
    }
}

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