2012-06-05 22 views
1

我是相當新的Javascript和我似乎無法得到一個腳本來運行/不上某些網頁上。使用Javascript - 如果URL中包含X,忽視劇本,否則,運行腳本

我有我的主網頁上運行此腳本來隱藏和取消隱藏內容:

$(document).ready(function() { 
$(".hidden").hide(); 
$(".show").html("[+]"); 
$(".show").click(function() { 
    if (this.className.indexOf('clicked') != -1) { 
     $(this).prev().slideUp(0); 
     $(this).removeClass('clicked') 
     $(this).html("[+]"); 
     } 
     else { 
     $(this).addClass('clicked') 
     $(this).prev().slideDown(0); 
     $(this).html("[–]"); 
     } 
    }); 
}); 

我需要一些編碼是這樣的:

如果URL中包含「/後/」則忽略腳本 其他運行腳本

這應該是一個簡單的解決。我只是無法讓它工作。有什麼建議麼?

回答

2

if你要找的是:

if (window.location.indexOf('/post/') == -1){ 
    // don't run, the '/post/' string wasn't found 
} 
else { 
    // run 
} 

indexOf()回報-1如果沒有找到該字符串,否則返回在字符串的第一個字符是字符串中的索引。

上述改寫由Jason提供加入常識(在評論,下圖):

if (window.location.indexOf('/post/') > -1){ 
    // run, the '/post/' string was found 
} 
+2

我會寫此爲'如果(window.location.indexOf( '/後/')> = 0){//代碼在這裏運行}',以避免(混淆)空如果塊。 –

1

根據this answer

window.location是一個對象,而不是字符串,所以它不具有 indexOf功能。

...所以window.location.indexOf()將永遠不會工作。

然而,由相同的答案爲指導,你可以在URL轉換爲字符串window.location.href來,然後進行搜索。精確匹配

window.location.pathname.split('/')得到URL的一部分

if (window.location.pathname === '/about/faculty/'){ ... },如this answer提到的:或者你可以訪問部分的URL,像這樣。

相關問題