【问题标题】:If statement with url plus universal variable带有 url 和通用变量的 if 语句
【发布时间】:2011-12-19 19:09:05
【问题描述】:

我正在尝试将博客上的博客转变为网站。为了有一个静态主页,我使用下面的 Javascript 代码来查看用户是否在主页上,如果他们在,那么它将隐藏帖子部分并显示主页“小工具”。有什么应该匹配的吗?

document.onload = hidepage();

function hidepage () {
 if (window.location == "http://website.blogspot.com/" || window.location == "http://website.blogspot.com/?zx=" + ANYTHING) { 
 //Checks to see if user is on the home page
  $(".hentry").hide(); //Hide posts
  $(".hfeed").hide(); //Hide posts
 }
 else {
  $("#HTML2").hide(); //hide gadget
 }

 $(".post-title").hide();  //Hide post titles
}

【问题讨论】:

  • 这不是问题,所以我不确定您需要什么帮助。

标签: javascript url variables if-statement character


【解决方案1】:

根据您所说的,我认为您想将 if 条件更改为:

if (window.location.href === "http://website.blogspot.com/" || 
    window.location.href.indexOf("http://website.blogspot.com/?zx=") > -1)

您也可以将其缩短为:

 if (window.location.href === "http://website.blogspot.com/" || 
    window.location.href.indexOf("/?zx=") > -1)

请注意,我已将您的 == 更改为 ===,因为后者是文字比较。

【讨论】:

  • 这是一个错字,应该是> -1...位置没有indexOf的方法,它应该是location.href.indexOf
  • 不过,为什么不=== 0?此外,location 对象不是字符串,因此 location === <any string> 将始终为 false。 developer.mozilla.org/en/DOM/window.location
  • 我没有使用=== 0,因为我很少使用包括http在内的完整URL...我的第二个例子是我倾向于做的。真的只是个人喜好。
  • 在我看来更合乎逻辑的是,结果可能是 0、1、2、3、25 等,> -1 更合适;因为它更好地代表了我正在测试的内容(即结果是否大于-1)。对!= 1 的测试意味着在一些疯狂的、不可能的情况下"myimpossiblestring" 的结果将返回true。即使它不太可能/不可能,我也不愿意写...这只是个人喜好。
【解决方案2】:

只需在if 表达式的后半部分使用String.indexOf

var url = window.location.href;
if (url === "http://website.blogspot.com/" || url.indexOf("http://website.blogspot.com/?zx=") === 0) {
    // do stuff
}

【讨论】:

    猜你喜欢
    • 2015-04-11
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 2016-02-18
    • 1970-01-01
    • 2013-10-12
    相关资源
    最近更新 更多