javascript - 循环遍历数组的 if 语句不起作用

标签 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上部 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/

相关文章:

javascript中的javascript,传递变量

javascript - 如何从 Internet Explorer 发送名为 Cookie 的请求 header ?

javascript - 我应该在每个文件中都需要一个模块还是需要一次并将其作为参数传递?

javascript - 如果语句不起作用,可能是一些基本问题

java - 这段java代码有什么问题。 Eclipse 中显示 "Terminated Application"

javascript - 在 Javascript 的继承类中声明 getter/setter

javascript - 在 IE 中触发拼写更正的 OnChange 事件

PHP:if($result = someFunction()) 是如何工作的?

linux - Bash 脚本条件

java - 如何使用 "if"语句