Prevent jquery show/hide div to goto top of page
The following script works for me to show a certain div when clicking a link and hiding any other that might be shown (so that only one is shown at a time). But the script also goes to top when clicking a link. How can I aboid that.
Code:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$('a').click(function () {
var divname= this.name;
$("#"+divname).show("slow").siblings().hide("slow");
});
});
</script>
</head>
<body>
<ul>
<li><a href="#" name="div1" >Show div1</a></li>
<li><a href="#" name="div2" >Show div2</a></li>
<li><a href="#" name="div3" >Show div3</a></li>
<li><a href="#" name="div4" >Show div4</a></li>
</ul>
<div>
<div id="div1" style="display:none">
This is div1
</div>
<div id="div2" style="display:none">
This is 开发者_开发技巧div2
</div>
<div id="div3" style="display:none">
This is div3
</div>
<div id="div4" style="display:none">
This is div4
</div>
</div>
</body>
</html>
The reason for that is the #
in your hrefs. Just use return false;
as the last statement in your click handler to prevent that.
$('a').click(function (e) {
e.preventDefault();
var divname= this.name;
$("#"+divname).show("slow").siblings().hide("slow");
});
look here jQuery event.preventDefault
use both e.preventDefault()
and return false;
for safety
I have not found a solution to this, and you must completely avoid the return false as this breaks accessibility.
When you click the link, the focus is on the target div, so if you use keyboard you will navigate through the div you have selected.
Using return false means the focus is at the top of the page, so the user would have to tab through the entire page every time, to get to where they want.
I would post this as a reply to other answers, however I cannot see any way to do that.
Use event.preventDefault();
after $('a').click(function ()
It will be something like:
<script>
$(document).ready(function(){
$('a').click(function () {
event.preventDefault();
var divname= this.name;
$("#"+divname).show("slow").siblings().hide("slow");
});
});
</script>
精彩评论