我有一个 html 页面,我想在 html 页面中通过 Javascript 检索 html 文档的名称。那可能吗?
例如 html 的名称document = "indexOLD.html"
我有一个 html 页面,我想在 html 页面中通过 Javascript 检索 html 文档的名称。那可能吗?
例如 html 的名称document = "indexOLD.html"
var path = window.location.pathname;
var page = path.split("/").pop();
console.log( page );
当前页面:可以做得更短。这一行听起来更优雅,可以找到当前页面的文件名:
var fileName = location.href.split("/").slice(-1);
或者...
var fileName = location.pathname.split("/").slice(-1)
自定义导航框的链接很酷,因此指向当前的链接是由 CSS 类启发的。
JS:
$('.menu a').each(function() {
if ($(this).attr('href') == location.href.split("/").slice(-1)){ $(this).addClass('curent_page'); }
});
CSS:
a.current_page { font-size: 2em; color: red; }
试试这个
location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
location.pathname 给出页面 URL 的部分(不包括域)。要仅获取文件名,您必须使用 substring 方法提取它。
采用:location.pathname
alert(location.pathname);
https://developer.mozilla.org/en-US/docs/DOM/window.location
即使 url 以 a 结尾,这也将起作用/
:
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);
用于window.location.pathname
获取当前页面 URL 的路径。
获取文档名称
location.href.split("/").pop().split("?").shift();
使用查询字符串
location.href.split("/").pop()
与斜杠一起使用的单个语句。如果您使用的是 IE11,则必须填充该filter
函数。
var name = window.location.pathname
.split("/")
.filter(function (c) { return c.length;})
.pop();
@Ethan的解决方案是我所需要的,但我必须做出一些改变。也就是说,toDelete 数组中的元素没有考虑到从数组段中删除元素会减少它们的数量。所以这是我的两便士:
let segments = window.location.pathname.split('/');
let toDelete = [];
for (let i = 0; i < segments.length; i++) {
if (segments[i].length < 1) {
toDelete.push(i);
}
for (let i = 0; i < toDelete.length; i++ ) {
segments.splice(toDelete[i], 1);
for (let j = i; j < toDelete.length; j++ ) {
(toDelete[j])--;
}
}
let filename = segments[segments.length - 1];
console.log(filename);
const page = location.href.split("/").slice(-1).toString().replace(".EXTENSION", "").split("?")[0];
这将获得页面名称,同时删除扩展名(如 .html 或 .php)并最终获得所有参数,如 (?id=1)。如果您没有扩展名,则可以删除该replace()
部分,否则将 .EXTENSION 替换为您喜欢的扩展名。
如果你想检查它是否在 URL 的末尾有路径“indexOLD.html”,你也可以使用它:
if(window.location.pathname.endsWith("indexODL.html")) {
// your code block here.
}
这些链接有助于了解有关每个可用全局接口(例如 window.xml)的更多信息。https://www.w3schools.com/js/js_window_location.asp , https://www.studytonight.com/javascript/javascript-window-object