2015-12-08 46 views
-4

当用户点击li链接时,我希望用户重定向到#gameshowintro。我如何重定向li链接?

HTML代码:

<li class="about"><a href="#gameshowintro"></a></li> 

的javascript:

$(document).ready(function() { 

    $("body").css("display", "none"); 

    $("body").fadeIn(2000); 

    $("a").click(function(event){ 
     event.preventDefault(); 
     linkLocation = this.href; 
     $("body").fadeOut(1000, redirectPage);  
    }); 

    function redirectPage() { 
     window.location = linkLocation; 
    } 

}); 
+1

你想重定向或滚动到那个地方? –

+0

我希望它重定向,具有淡出效果。 –

+1

它不是不在同一页吗? –

回答

0

为了让你的代码工作,你需要将linkLocation传递给函数。 linkLocation而不是 a 全局范围变量(它是本地的click事件处理程序函数),它不能从被调用的函数访问。所以,你的代码更改为:

$("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; 
     } 
    } 
    }); 
}); 
+0

OP意味着当点击“li”时,必须访问里面的'a'标签。 –

+0

@JacquesMarais更新了答案。请看一看。 –

+0

您不需要将'linkLocation'传递给该函数,没有'var'关键字的变量集合总是全局的,并且该函数在变量设置后运行。 –