如果URL包含字符串然后运行jQuery函数?

在我的网站上,如果我的url包含“测试”一词,我就会运行jQuery函数

我试图做的就是如果我的url包含’rest’字符串,那么为页面上的元素添加边距?

我添加了一个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') }); 

使用window.location获取当前位置的URL。

根据条件,您可以应用margin top属性。

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

请查看此链接,其中包含您需要了解的有关URL的详细信息。

https://developer.mozilla.org/en-US/docs/DOM/window.location

 $(document).ready(function(){ if (window.location.href.indexOf('rest') >= 0) { $('.block-widget').css('margin-top, 252px') } }); 

获取路径名称:

var pathname = window.location.pathname;

然后检查它是否包含“TEST”。

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

试试这个

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

name * =’keyword’选择器是true选项。

      

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