2011-12-19 54 views
1

我试图将博客上的博客转换为网站。为了有一个静态主页,我使用下面的Javascript代码来查看用户是否在主页上,如果他们是,那么它将隐藏帖子部分并显示主页“小工具”。任何东西都应该匹配什么?如果语句带有url加上通用变量

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 
} 
+0

这不是问题,所以我不确定你想要帮助什么。 – JesseBuesking 2011-12-19 19:11:25

回答

1

if表达的第二半只需使用String.indexOf

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

根据你说的话我想你想改变,如果条件:

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) 

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

+0

为什么'> 0'而不是'=== 0'? – 2011-12-19 19:13:32

+0

这是一个错字,应该做'> -1' ...位置没有'indexOf'的方法,它应该是'location.href.indexOf' – isNaN1247 2011-12-19 19:16:26

+0

仍然,为什么不是'=== 0'?另外,一个'location'对象不是一个字符串,所以'location === ''将永远是错误的。 https://developer.mozilla.org/en/DOM/window.location – 2011-12-19 19:17:08