2013-01-22 39 views
1

一個非常簡單的問題,但我想不起在google上搜索「正確」的單詞。我的問題是我想讓鏈接'歷史'仍然可見後,我點擊它。我不想讓頁面轉到div,而只是更改內容。我知道我需要jQuery來隱藏/切換內容,但我被困在鏈接部分。使id鏈接可見 - 防止單擊錨點時的默認事件。

#goals{ 
display    : none; 
} 

#history{ 
display    : block; 
} 

<p ><a id="History" href="#history"> <b>History</b> </a></p> 
<p ><a id="Goals" href="#goals"> <b>Goals</b> </a></p> 

<div id="history"> 
<p> blah blah blah </p> 
</div> 

<div id="goals"> 
<p> blah blah blah </p> 
</div> 

$("#Goals").click(function(){ 
     $("#history).hide(); 
     $("#goals").show(); 
}) 
+0

你需要JavaScript才能取消鏈接的默認操作,你是否嘗試過任何東西 – j08691

+0

我看了看這個:http://stackoverflow.com/questions/5089834/如何使jQuery的子菜單保持可見後點擊 但s解決方案對我不起作用。 – user977151

+0

發佈您的完整代碼。 #歷史如何隱藏在第一位? – matthewpavkov

回答

1

您需要調用傳遞給您的處理程序的event參數的preventDefault()方法。例如:

<a id="historyLink" href="#">History</a> 

......還有......

$('#historyLink').click(function(e){ 
    e.preventDefault(); // block the default action 
    // do something 
}); 
+0

謝謝!我想出了切換內容,但我仍然困擾着href問題。完全忘了你可以放'#'把它保留爲鏈接。 – user977151

0

你不需要CSS,你可以用jQuery做到這一切:

HTML

<p ><a id="History" href="#history"> <b>History</b> </a></p> 
<p ><a id="Goals" href="#goals"> <b>Goals</b> </a></p> 

<div id="history"> 
<p> history blah blah blah </p> 
</div> 

<div id="goals"> 
<p> goals blah blah blah </p> 
</div> 

的jQuery

$("#goals").hide(); 

$("#Goals").click(function(){ 
    $("#history").hide(); 
    $("#goals").show(); 
}); 

$("#History").click(function(){ 
    $("#goals").hide(); 
    $("#history").show(); 
}); 

這是jsFiddle將它們連接在一起。

+0

是的,我做到了,除了'$(「#goals」)。hide();'。它現在似乎工作。謝謝 – user977151

0

你頁面移動的原因是因爲這是一個錨單擊事件的默認操作。 你需要做的是確保該默認操作不會發生(這是負責你的頁面上的「運動」 我建議如下:

<!-- you don't need to link it to the actual id, since you are toggling the visibility using jQuery --> 
<a id="historyLink" href="#">History</a> 

然後,就jQuery的關注:?

$('#historyLink').click(function(event){ 
    //prevent the page from scrolling 
    event.preventDefault(); 
    //possibly hide the other div if it is visible 
    $('#theotherdiv').hide(); 
    //show the div 
    $('#historyLink').show(); 
});