JavaScript当前URL检查

Sam*_*ows 4 javascript

我想知道如何让JavaScript检查用户是否在某个URL上,这样我就可以从结果中构建一个if语句.

我的理由是,如果用户点击菜单中的链接并且他们当前在trucks.php上,则javascript会将它们重定向到某个页面.如果他们不在truck.php上,他们将被引导到另一页.

干杯伙计们.

Thi*_*ter 10

当前位置是location.href.

location对象还包含一些其他有用的字段:

  • location.hash:URL中#后面的部分
  • location.host:包含端口的主机名(如果指定)
  • location.hostname:只是主机名
  • location.pathname:没有协议/主机/端口的请求URI; 以/开头
  • location.port:端口 - 仅在URL中指定了一个端口
  • location.protocol:通常是'http:'或'https:' - 记住结尾的冒号

在您的情况下,检查文件名是否为trucks.php的最安全的方法是:

var parts = location.pathname.split('/');
if(parts[parts.length - 1] == 'trucks.php') {
    location.href = 'some-other-page';
}
Run Code Online (Sandbox Code Playgroud)

如果要在不保留当前页面的情况下重定向,请使用以下代码而不是location.href分配:

location.replace('some-other-page');
Run Code Online (Sandbox Code Playgroud)