2012-09-21 43 views
4

在我的網站id喜歡運行一個jQuery函數,如果我的網址包含單詞'測試'如果URL包含字符串,然後運行jQuery函數?

所有我試圖做的是如果我的網址包含'休息'字符串,然後頁邊上添加一個元素?

我添加了一個jSfiddle來試圖展示我到目前爲止所做的工作。

$(document).ready(function(){   
    // How can I check to see if my url contains the word 'TEST' then run the below function? 
    $('.block-widget').css('margin-top, 252px')  
}); 

回答

9

使用window.location來獲得當前位置的URL。基於你就可以申請保證金頂級物業的條件

$(document).ready(function(){   
    var pathname = window.location.pathname; 
    if(pathname.indexOf('text') > -1){ 
     $('.block-widget').css('margin-top, 252px'); 
    }  
}); 
+1

我不認爲該路徑是'test'可以/應該出現 – Bergi

+0

@Bergi我們假設OP知道有足夠的瞭解編程檢查'窗口的唯一部分。位置「本身並找到解決方案。 :D – omninonsense

2
$(document).ready(function(){   
    if (document.url.match(/test/g)){ 
    $('.block-widget').css('margin-top, 252px')  
    } 
}); 
0

獲取路徑名:

var pathname = window.location.pathname;

然後檢查它是否包含 「TEST」。

if (pathname.toLowerCase().indexOf("test") >= 0)

+0

你正在使用toLowerCase(),所以你應該檢查'測試' – Steve

+0

@Steve:是的,你是對的!我編輯它。 – Max

0

試試這個

$(document).ready(function(){   
    var patt=/test/g; 
    if(patt.test(window.location.pathname)){ 
    $('.block-widget').css('margin-top, 252px') 
    } 

}); 
0

名* = '關鍵字'選擇是正確的選擇。

<input name="man-news"> 
<input name="milkman"> 
<input name="letterman2"> 
<input name="newmilk"> 

<script> 
$("input[name*='man']").val("has man in it!"); 
</script> 

資源:https://api.jquery.com/attribute-contains-selector/

相關問題