Javascript 使用window.location更改页面

Javascript 使用window.location更改页面,javascript,jquery,html,Javascript,Jquery,Html,我真的不知道该怎么称呼这个。我使用jQuery,因此当用户单击div时,它会将其转移到基于div类的页面: window.location = $(this).attr('class'); 假设我正在从Web服务器(本地主机)连接。第一次点击可能会让我想起 localhost/info localhost/info/about 如果我点击about,它会把我带到 localhost/info localhost/info/about 我想知道如何让它把我转到 localhost/abo

我真的不知道该怎么称呼这个。我使用jQuery,因此当用户单击div时,它会将其转移到基于div类的页面:

window.location = $(this).attr('class');
假设我正在从Web服务器(本地主机)连接。第一次点击可能会让我想起

localhost/info
localhost/info/about
如果我点击about,它会把我带到

localhost/info
localhost/info/about
我想知道如何让它把我转到

localhost/about
而不是

localhost/info/about

您需要使用绝对路径而不是相对路径。要做到这一点,可以在类前面加上
/

window.location = "/" + $(this).attr('class');

首先,
位置
是一个对象。虽然分配给它确实有效,但最好分配给
location.href

另外,
class
是一个不好的属性选择,因为它非常有限。相反,您应该考虑数据属性:

<div data-href="/about"></div>
注:每次有人写
$(this).attr(…)
,一只独角兽就会死去