如果window.location.host属性等于特定值,如何加载不同的文档

时间:2012-12-20 15:09:55

标签: javascript html

我希望我的网站中的网页能够自动加载其他文档或执行window.location.host == "subdomain.mywebsite.com"代码块,如果window.location.host == "mywebsite.com"它应该加载新文档。

我已尝试将if ... else语句与逻辑运算符一起使用,但它似乎无效,这是我的代码。

<!DOCTYPE html>
<html>
<script>
  var ATurl=window.location.host;
  document.write(ATurl);
  if(ATurl == downloads.wping.tk) {
    document.write("--an html function to execute here--");
  )
  else {
    document.write("--another html function to execute here!--");
  }
 </script>
</html>

有人可以帮我解决问题。也许在某处错了!感谢

4 个答案:

答案 0 :(得分:2)

您的代码中有两个错误

    第8行
  • )应替换为} 正确关闭if语句

  • 第6行
  • if(ATurl == downloads.wping.tk) {
    您正试图在tk中访问wping downloads个属性 您想要将ATurl与字符串进行比较,以便将"放在downloads.wping.tk

  • 周围

然后你应该结束这个

<!DOCTYPE html>
<html>
<script>
  var ATurl= window.location.host;
  document.write(ATurl);
  if(ATurl == "downloads.wping.tk") {
    document.write("--an html function to execute here--");
  }
  else {
    document.write("--another html function to execute here!--");
  }
 </script>
</html>​

继承人Fiddle为你

答案 1 :(得分:1)

你需要在字符串周围加上引号。此外,您使用错误的括号类型(括号)

关闭了if
if (window.location.host == 'downloads.wping.tk') {
   // do something
} else {
   // do something else
}

答案 2 :(得分:0)

  ...
  ) //SHOULD BE A } HERE
  else {
  ...

答案 3 :(得分:0)

downloads.wping.tk没有达到您的预期。试试这个:

it( ATurl !== "mywebsite.com" ) {
    document.location = window.location.protocol + "://mywebsite.com/";
}

document.write()没有必要/没有意义。

还习惯于查看浏览器的JavaScript控制台,它会告诉您代码中的任何语法错误。