如何使用javascript获取当前页面

时间:2012-12-03 06:57:13

标签: javascript

我可以使用javascript获取当前页面吗?

例如,如果我到达子页面的主页,我将使用index.php的字符串名称,或者如果我转到about页面,我可以获得about.php

我试试这段代码: window.location.pathname

但是我在子域名中得到了这个。  /directory/new/index.php/directory/new/about.php

有没有人对我的案子有所了解?任何帮助将不胜感激。

5 个答案:

答案 0 :(得分:1)

window.location.hreftop.location.href 您将获得此页面的“http://stackoverflow.com/questions/13678553/how-to-get-the-current-page-using-javascript”。

`var url=window.location.href.split('/');
var name=url[url.length-1];`

name是index.php或about.php

答案 1 :(得分:1)

window.location.pathname.split("/").pop();

对于/directory/new/index.php,split(“/”)将返回[,“directory”,“new”,“index.php”],而pop()将返回最后一个元素index.php

答案 2 :(得分:0)

试试这个

window.location.href

答案 3 :(得分:0)

试试这个: document.URL

document.URL

window.location.href

window.location.href

答案 4 :(得分:0)

我认为你不能直接得到你想要的东西,试试这样:

var segments = window.location.pathname.split('/');
var result = segments[segments.length - 1];

以下是有关当前问题网址的数据:

hash: "#13678603"
host: "stackoverflow.com"
hostname: "stackoverflow.com"
href: "http://stackoverflow.com/questions/13678553/how-to-get-the-current-page-using-javascript/13678603#13678603"
origin: "http://stackoverflow.com"
pathname: "/questions/13678553/how-to-get-the-current-page-using-javascript/13678603"
port: ""
protocol: "http:"