Empty-linked anchor

廉价感情. 提交于 2019-12-01 05:14:07

In your onclick handler, add this to the end:

return false;

This will cancel the default processing (i.e. following the link) and you can put whatever you want in the href (the # is as good as any).

Ideally you would have an option for those with Javascript disabled:

<a href="degrade_option.html" onclick="return fancy_option();">do the option!</a>

If you're not into that sort of thing, although you really should be, the most common way is to use the pound but then cancel the event to prevent the default action from happening, like so:

<a href="#" onclick="return do_something();">do something</a>

But then you have to make sure do_something returns false. (or you can just add return false; at the end of the click handler, but this gets even more unsightly fast)

Although, to be honest, you really shouldn't have inline Javascript attributes to begin with. They are bad practice, a nightmare to maintain, and there are much better alternatives out there.

EDIT: In response to your comment, the alternative is unobtrusive javascript:

"Unobtrusive JavaScript" is an emerging technique in the JavaScript programming language, as used on the World Wide Web. Though the term is not formally defined, its basic principles are generally understood to include:

  • Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
  • Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
  • Progressive enhancement to support user agents that may not support advanced JavaScript functionality

Read the page for some examples.

<a href="javascript:void(0);" onclick="...">txt</a>

I prefer to drop the href (it's not required according to W3C spec) if it's not used. To get the expected mouse cursor, use CSS!

<style type="text/css">
a { cursor: pointer; }
</style>
<a onclick="go();">link</a>
<a href="javascript:;">Foo</a>

Short, descriptive and does not jump like #.

There are two ways of doing this, if the id tag of the link is link, you can use href="#"in your HTML, and then in your JavaScript have:

$('#link').click(function(evt) {
 // code goes here
 evt.preventDefault();
});

This prevents the browser's normal behavior. Or

$('#link').click(function(evt) {
 // code goes here
 return false;
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!