如何在 Javascript 中获取 html 页面的名称?

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

How can i get the name of an html page in Javascript?

javascripthtml

提问by programmer

i have an html page and i would like inside the html page to retrieve the name of the html document via Javascript. Is that possible?

我有一个 html 页面,我想在 html 页面中通过 Javascript 检索 html 文档的名称。那可能吗?

e.g. name of html document = "indexOLD.html"

例如 html 的名称 document = "indexOLD.html"

回答by Daniel Aranda

var path = window.location.pathname;
var page = path.split("/").pop();
console.log( page );

回答by Hugolpz

Current page: It's possible to do even shorter. This single line sound more elegant to find the current page's file name:

当前页面:可以做得更短。用这一行来查找当前页面的文件名听起来更优雅:

var fileName = location.href.split("/").slice(-1); 

or...

或者...

var fileName = location.pathname.split("/").slice(-1)

This is cool to customize nav box's link, so the link toward the current is enlighten by a CSS class.

自定义导航框的链接很酷,因此指向当前的链接由 CSS 类启发。

JS:

JS:

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

CSS:

CSS:

a.current_page { font-size: 2em; color: red; }

回答by Gaurang P

Try this

尝试这个

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

location.pathname gives the part(domain not included) of the page url. To get only the filename you have to extaract it using substring method.

location.pathname 给出页面 url 的部分(不包括域)。要仅获取文件名,您必须使用子字符串方法提取它。

回答by Naftali aka Neal

Use window.location.pathnameto get the path of the current page's URL.

使用window.location.pathname来获取当前页面的URL路径。

回答by Ethan

This will work even if the url ends with a /:

即使 url 以 结尾,这也会起作用/

var segments = window.location.pathname.split('/');
var toDelete = [];
for (var i = 0; i < segments.length; i++) {
    if (segments[i].length < 1) {
        toDelete.push(i);
    }
}
for (var i = 0; i < toDelete.length; i++) {
    segments.splice(i, 1);
}
var filename = segments[segments.length - 1];
console.log(filename);

回答by rebelzach

Single statement that works with trailing slash. If you are using IE11 you'll have to polyfillthe filterfunction.

与尾随斜杠一起使用的单个语句。如果您使用的是 IE11,则必须对函数进行polyfillfilter

var name = window.location.pathname
        .split("/")
        .filter(function (c) { return c.length;})
        .pop();