How do I prevent redirection after clicking a hyperlink?

I have the following html + js code:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>

<a href="#" id=key onclick="func(0)">foo</a>

</body>

<script type="text/javascript">
function func(k){
    alert(1);
    return false;
}   
</script>
</html>

      

Can you explain how to refactor the following code that, after clicking on the href code, func

executes, but # does not add the url and the page should not reload?

+5


source to share


5 answers


Use javascript:void(0);

instead #

like this:



<a href="javascript:void(0);" id="key" onclick="func(0)">foo</a>

      

+6


source


You can simply remove the href attribute:



<a id='key' onclick="func(0)">foo</a>

      

+4


source


Change it to:

                            vvvvvvv
<a href="#" id=key onclick="return func(0)">foo</a>

      

+4


source


I think you forgot the quotes in the "key"

<a href="#" id="key" onclick="func(0)">foo</a>

0


source


To be more semantically correct, I would use a button with the following onclick:

<button id=key onclick="return func(0)">foo</button>

      

So there is no need to hack e.preventDefault / return false.

0


source







All Articles