How to prevent reload with onclick without “#”?

2019-01-22 13:41发布

问题:

I wish to put some instructions with a link - onclick calling a script that display a simple alert box. If I did like this...

<label for="arquivo">Máximo de 1MB, observe os <a href="" onclick="ajudaUpload();">tipos permitidos</a>.</label>

the page is reloaded even with a return false, and if I did like this...

<label for="arquivo">Máximo de 1MB, observe os <a href="#" onclick="ajudaUpload();">tipos permitidos</a>.</label>

with the "#" symbol, the page is scrolled to the top and "#" is added to query string. Is there a third way to do it without reloading, scrolling and garbage?

回答1:

Return false after the call:

<a href="" onclick="ajudaUpload();return false;">tipos permitidos</a>

Or if your function returns false then you can return the result of the function:

<a href="" onclick="return ajudaUpload();">tipos permitidos</a>

It's not enough to just return false in the function, you need to actually return false from the click handler.



回答2:

You can use .preventDefault() method, or return false, or remove the HREF tag all together. Either should work just fine.

Vc nao deviar estar usando onclick dessa forma pra comecar. Ja eh bem antigo e nao se usa assim mais.



回答3:

<a href="" onclick="return ajudaUpload()">tipos permitidos</a>

and then return false in your function:

function ajudaUpload()
{
  ...
  return false;
}


回答4:

You can use:

<a href = "javascript:void(0);" onclick="ajudaUpload();"> 

Even I was stuck on a similar problem. I wanted to use onclick function but the page would reload, which I didn't want. I tried href = "javascript:void(0);" and it worked.



回答5:

Very simple way to do this is just add '?' (questionmark) :)

F.e.

<a href="#?">Moiz Travadi</a>


回答6:

Almost any element suports onclick events, so you can use a b tag, or a button tag, even an span tag. Then you can style it to look just like a link (a tag), or any other way you want. For example:

<label for="arquivo">Máximo de 1MB, observe os <b onclick="ajudaUpload();">tipos permitidos</b>.</label>


回答7:

Remove your herf and give id for your tag. Then by using id you can show your alert. ('#id').click(function (){alert(message); return false; });