asp.net page reloading on javascript onclick function
Novice question I guess:
The Scenario:
I have an asp.net page that contains 6 divs and 6 hyperlinks which are linked to javascript function:function showdiv(divname)
{
hideallcontentdivs();
var targetdiv = document.getElementById(divname);
targetdiv.style.display="block";
}
var alldivs=new Array();
function hideallcontentdivs()
{
alldivs=开发者_开发技巧document.getElementsByTagName("div");
for(var i=0; i<alldivs.length;i++)
{
if(alldivs[i].className=="content")
{
alldivs[i].style.display="none";
}
}
}
ImageButton:
<a href="" onclick="showdiv('item1');"><img alt="alternate_text" src="imagesource" border="0px" /></a>
the divs have id's: item1, item2....item6 and the hyperlink specify to the javascript function the id of the div that needs to displayed.
The Problem:
Whenever I click on an hyperlink, the effect that I want is achieved but the page reloads too. Don't really know where I'm going wrong but if anyone could guide me in the right direction, I'll be very very thankful.Just return false on click
onclick="showdiv('item1');return false;"
Update:I just point the issue :), you can return the false where ever you like.
onclick="return showdiv('item1');"
and say to showdiv() to return false
You should add return false
to your onclick handler. This prevents the default behaviour of the link.
A better solution would be to use jQuery or some other library and attach the event to the element. They also contain special functions to prevent the default behaviour:
Html:
<a id="button1" href="#"><img alt="alternate_text" src="imagesource" /></a>
Javascript/jQuery:
$('#button1').click(function(event) {
$('div').hide(); // hides all divs
$('#div1').show(); // shows the div with the id 'div1'
event.preventDefault(); // prevents postback
});
always, return false :)
but i'd rather put it in the function
function showdiv(divname)
{
hideallcontentdivs();
var targetdiv = document.getElementById(divname);
targetdiv.style.display="block";
return false;
}
+1 for Aristos' answer, although if you refactor the return false;
to the end of the showdiv
function you want have to update all the links.
return false
is the key, as the other answers have said.
Just to add my tuppence though: you don't really need to use an anchor here and imho it's not good semantic style. Just use a span or div instead, and then the problem goes away.
精彩评论