从地址栏中获取页面文件名

Boa*_*rdy 29 html javascript jquery

我想知道是否可以使用jquery或javascript从地址栏中获取页面名称.我知道这可以使用PHP完成,但不是真的想要,因为它只是一个HTML网站.

即如果地址是www.mywebsite.com/hello.htm如何从地址中获取该hello.htm部分.

感谢您的任何帮助,您可以提供.

Sha*_*oli 60

试试这个

location.pathname.substring(location.pathname.lastIndexOf("/") + 1);

location.pathname给出页面网址的部分(不包括域).要只获取文件名,您必须使用substring方法来提取它.


Jua*_*des 53

https://developer.mozilla.org/en/DOM/window.location

alert(location.pathname)
Run Code Online (Sandbox Code Playgroud)

如果您不想要前导斜杠,可以将其删除.

location.pathname.substring(1)
Run Code Online (Sandbox Code Playgroud)


Hug*_*lpz 5

当前页面:单行声音更加优雅,可以找到当前页面的文件名:

location.href.split("/").slice(-1)
Run Code Online (Sandbox Code Playgroud)

要么

location.pathname.split("/").slice(-1)
Run Code Online (Sandbox Code Playgroud)

这很容易定制导航框的链接,因此当前的链接是由CSS类启发的.

JS:

$('.menu a').each(function() {
    if ($(this).attr('href') == location.href.split("/").slice(-1)){ $(this).addClass('curent_page'); }
});
Run Code Online (Sandbox Code Playgroud)

CSS:

a.current_page { font-size: 2em; color: red; }
Run Code Online (Sandbox Code Playgroud)