我想知道如何让JavaScript检查用户是否在某个网址上,这样我就可以根据结果构建一个if语句。
我的推理是,如果用户点击菜单中的一个链接,而他们当前在trucks.php上,javascript会将他们重定向到某个页面。如果他们不在trucks.php上,他们将被定向到不同的页面。
干杯伙计们。
发布于 2010-12-02 22:03:35
当前位置在location.href中。
location对象还包含一些其他有用的字段:
处的冒号
在您的例子中,检查文件名是否为trucks.php的最安全的方法是:
var parts = location.pathname.split('/');
if(parts[parts.length - 1] == 'trucks.php') {
location.href = 'some-other-page';
}如果要重定向而不将当前页面保留在历史记录中,请使用以下代码而不是location.href赋值:
location.replace('some-other-page');发布于 2010-12-02 22:03:34
使用window.location.href获取当前URL,或使用window.location.pathname仅获取路径。对于您的具体问题,解决方案只需要路径名:
if (window.location.pathname == "/trucks.php")
window.location = "/somewhereelse.php";发布于 2010-12-02 22:04:07
使用window.location
https://stackoverflow.com/questions/4335784
复制相似问题