How can I create an empty HTML anchor so the page doesn't “jump up” when I click it?

こ雲淡風輕ζ 提交于 2019-11-28 16:47:57

Put a "return false;" on the second option:

<a href="" onclick="jquery_stuff; return false;" />

You need to return false; after the jquery_stuff:

<a href="no-javascript.html" onclick="jquery_stuff(); return false;" />

This will cancel the default action.

Shiva Srikanth Thummidi

You can put simply as like below:

<a href="javascript:;" onclick="jquery_stuff">

jQuery has a function built in for this called preventDefault which can be found here: http://api.jquery.com/event.preventDefault/

Here's their example:

<script>
$("a").click(function(event) {
    event.preventDefault();
});
</script>

You can also build the link like this:

<a href="javascript:void(0)" onclick="myJsFunc();">Link</a>
Chris

Check eyelidlessness' comment (use a button, not an anchor). Was just about to post the same advice. An anchor that doesn't link to a resource and merely executes a script should be implemented as a button.

Stop putting your event handlers in HTML, and stop using anchor tags that don't serve anchor semantic purposes. Use a button and add the click handler in your Javascript. Example: HTML <button id="jquery_stuff">Label</button> and JavaScript $('#jquery_stuff').click(jquery_stuff);. You can use CSS to style the button to look like a link, by removing padding, borders, margin and background-color, then adding your link styles (eg. color and text-decoration). – eyelidlessness Oct 19 '10 at 17:40

Dean
<a href="javascript:;" onclick="jquery">link</a>

href requires something in there if you want it to not pop up errors in validators for html. The javascript:; is a good place holder.

If you really want to use the #:

<a href="#me" name="me" onclick="jquery">link</a>

Be careful with the return false;, it halts default behaviours of whatever you are doing.

Also if your js is like a submit you may run into problems in internet explorer.

<a href="javascript:// some helpful comment " onclick="jquery_stuff" />

I usually use a <span> and style it to look like a link when I need to accomplish something like this.

  <a href="#" class="falseLinks">Link1</a>
  <a href="#" class="falseLinks">Link2</a>

etc..

JQUERY:

  $(function() {
    $("a.falseLinks").click(function() {
      // ...other stuff you want to do when links is clicked

      // This is the same as putting onclick="return false;" in HTML
     return false;
    })
  });

@eyelidlessness was a bit douchy in the way he said it but he was right. This is the cleanest way to do it. Why use jQuery if you're then gonna go back to vanilla Javascript for stuff jQuery does easier and cleaner?

Usually I do:

<a style="cursor:pointer;" onclick="whatever();">Whatever</a>

How about this:

<a href="#nogo" onclick="foo();">some text</a>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!