2013-01-22 102 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(); 
});