2015-12-08 44 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'關鍵字的變量集合總是全局的,並且該函數在變量設置後運行。 –