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



我希望我的网站中的网页自动加载其他文档或执行代码块,如果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>

有人可以帮助我处理代码。也许某个地方错了!谢谢

您的代码中有两个错误

  • 在第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>​

Heres for You

您需要在字符串周围添加报价标记。另外,您以错误类型的支架(括号)

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

downloads.wping.tk不执行您的期望。尝试以下操作:

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

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

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

最新更新