开发者

Page jumps to the top onclick [duplicate]

开发者 https://www.devze.com 2023-02-05 02:24 出处:网络
This question already has answers here: Prevent href="#" link from changing the URL hash (11 answers)
This question already has answers here: Prevent href="#" link from changing the URL hash (11 answers) Closed 8 years ago.

I have a click in the middle of a website with code like <a href=“#“ onclick=“…

The function works well, but the a href=“#“ let’s the page always jump to the top when I click on the li开发者_如何学Gonk. Is there any way around it?

Thanks


Just add ; return false; to the end of your onclick, for example:

<a href="#" onclick="alert('hello'); return false;">

Edit: Hemlock's answer is a good alternative, but yet another one is a combination of the two:

<a href="javascript:void(0)" onclick="alert('hello')">

The advantage of this is that you're explicitly saying that the <a> should do nothing with the href, and the onclick event handler is a separate attribute. If you later decide to attach the onclick handler using JavaScript rather than inlining it (recommended), it's simply a matter of removing the onclick attribute.


Alternate method

<a href="javascript: alert('hello'); void(0);"></a>

Put the javascript in the href and make sure the code ends in a call to void


add

return false;

at the end of the onclick statement

that is

<a href="#" onclick="alert('test'); return false;"> Click Here </a>


if you want an element that does some javascript onclick, you should not use the a tag. The a tag is for navigation from one page to another. You should use span and then you don't have to provide a href attribute. The problem lies in the fact that you chose the wrong HTML element for your case.

<span onclick=""></span>
0

精彩评论

暂无评论...
验证码 换一张
取 消