Javascript 如何重定向li a href链接?
当用户单击li链接时,我希望用户重定向到#gameshowintro Html代码:Javascript 如何重定向li a href链接?,javascript,jquery,html,Javascript,Jquery,Html,当用户单击li链接时,我希望用户重定向到#gameshowintro Html代码: <li class="about"><a href="#gameshowintro"></a></li> 要使代码正常工作,需要将linkLocation传递给函数。linkLocation是not一个全局范围变量(它是click事件处理程序函数的本地变量),无法从调用的函数访问该变量。因此,请将代码更改为: $("a").click(function(even
<li class="about"><a href="#gameshowintro"></a></li>
要使代码正常工作,需要将
linkLocation
传递给函数。linkLocation
是not一个全局范围变量(它是click
事件处理程序函数的本地变量),无法从调用的函数访问该变量。因此,请将代码更改为:
$("a").click(function(event){
event.preventDefault();
linkLocation = this.href;
$("body").fadeOut(1000, "redirectPage('" + linkLocation + "')");
});
function redirectPage(linkLocation) {
window.location = linkLocation;
}
或者如果您需要滚动到该部分。如果是这种情况,请使用此平滑滚动:
你想被重定向或滚动到那个地方吗?我希望它被重定向,并具有淡出效果。它不在同一页吗?@JacquesMarais更新了答案。请看一看。您不需要将
linkLocation
传递给函数,没有var
关键字的变量集始终是全局的,函数在变量设置后运行。@Jacquesmaais再次检查代码。它有一个局部范围。请
$("a").click(function(event){
event.preventDefault();
linkLocation = this.href;
$("body").fadeOut(1000, "redirectPage('" + linkLocation + "')");
});
function redirectPage(linkLocation) {
window.location = linkLocation;
}
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});