2011-12-19 53 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