javascript 如果 URL 包含字符串,则运行 jQuery 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12534245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:27:40  来源:igfitidea点击:

If URL contains string then run jQuery function?

javascriptjquery

提问by Liam

On my website id like to run a jQuery function if my url contains the word 'test'

如果我的 url 包含“test”这个词,我的网站 id 喜欢运行 jQuery 函数

All im trying to do is if my url contains the 'rest' string then add a margin to an element on the page?

我想要做的就是如果我的 url 包含“rest”字符串,然后向页面上的元素添加边距?

Ive added a jSfiddle to try and show what Ive done so far.

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

回答by Sushanth --

Use window.locationto get the current location url..

使用window.location来获得当前位置的URL ..

Based on the condition you can then apply the margin top property.

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

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

回答by balafi

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

回答by Selvakumar Arumugam

Take a look at this link that contains details that you need to know about URL.

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

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

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')     
    }
});

回答by Max

Get the path name:

获取路径名:

var pathname = window.location.pathname;

var pathname = window.location.pathname;

Then check if it contains "TEST".

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

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

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

回答by Anton Baksheiev

try this

试试这个

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

});

回答by Sedat Kumcu

name*='keyword'selector is true option.

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

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

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

Resource: https://api.jquery.com/attribute-contains-selector/

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