如果 URL 包含此内容,请在 Javascript 中执行此操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2850467/
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-08-23 02:10:26  来源:igfitidea点击:

If the URL contains this do that in Javascript

javascript

提问by Sam

I want to display a certain message on a certain page.

我想在某个页面上显示某个消息。

Suppose the name of the page I want to display something on is called "foo_page.html",

假设我想显示内容的页面名称叫做“foo_page.html”,

How can I do this using javascript?

我怎样才能使用 javascript 做到这一点?

回答by GShenanigan

You can do it like this:

你可以这样做:

if(document.URL.indexOf("foo_page.html") >= 0){ 
...show your message
}

回答by zaf

The following will show an alert box if the url is something like http://example.com/foo_page.html:

如果 url 类似于http://example.com/foo_page.html,以下将显示一个警告框:

if(location.pathname=="/foo_page.html") alert('hey!');

回答by Gregtheitroade

var index = document.location.lastIndexOf("/");
var filename = document.location.substr(index);

if(filename.indexOf("foo_page.html")>-1){
   alert("OK");
}

回答by EAMann

You can use document.locationto figure out what URL the visitor is at.

您可以使用它document.location来确定访问者所在的 URL。

Try this:

尝试这个:

<script type="text/javascript">
var currentPage = document.location.href.substring(document.location.href.lastIndexOf("/")+1, document.location.href.length);
</script>

Your "currentPage" variable should now contain the name of the page you're on. You can use that to select an action.

您的“currentPage”变量现在应该包含您所在页面的名称。您可以使用它来选择一个动作。

回答by meo

var loc = window.location.pathname.split("/"),
    size = loc.length

    alert(loc[size])

gives you the last part splitted by "/" most of the time the html, php or whatever file. But i would use classes on your body to recognize where you are. Or just check if the element you want to do something with exists on the page. Before you execute your function like this

大多数情况下,最后一部分是由“/”分割的 html、php 或任何文件。但我会使用你身体上的课程来识别你在哪里。或者只是检查页面上是否存在您要对其执行操作的元素。在你像这样执行你的功能之前

  function example(element) {
      if(getElementById(element).length) {
          // now you are sure that a element exists on the page
      }else{
         return false; //if not just do nothing
      }
  }
  example("myId")