我有这个代码:
$('.contentBox').click(redirect);
function redirect () {
var pathname = window.location.pathname
location.assign(pathname.replace('index.html', $(this).find('a').attr('href')));
return false;
}
这在本地主机上工作正常,但在服务器上它只是刷新主页。只有当我实际上先访问菜单上的另一个页面,然后使用该功能返回我的页面时,它才有效......什么给?
首先,您正在做的事情并不是重定向用户的最佳方式。直接使用 href 进行相同。
现在来看你的代码。只要路径名不包含 index.html,它就会始终刷新,您分配给 location.assign() 的内容是这样的:
pathname.replace('index.html', $(this).find('a').attr('href'))
如果路径名不包含索引.html它将返回路径名本身,这是您的原始路径。因此,您会看到页面刷新。
尝试添加console.log(pathname)
进行验证。
$('.contentBox').click(redirect);
function redirect () {
var pathname = window.location.pathname
console.log(pathname)
if(pathname.indexOf('index.html') > -1){
location.assign(pathname.replace('index.html', $(this).find('a').attr('href')));
return false;
}
}