最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

href="javascript:void(0)" vs. advanced disabling of links - Stack Overflow

programmeradmin6浏览0评论

I use

href="javascript:void(0)"

to disable the href property and then use onlclick to give functionality to my anchor elements. How can I do this programatically.

I use

href="javascript:void(0)"

to disable the href property and then use onlclick to give functionality to my anchor elements. How can I do this programatically.

Share Improve this question edited Aug 31, 2011 at 0:52 asked Aug 28, 2011 at 23:13 user656925user656925 1
  • so what is the question? does it work again if you remove the target="_blank"? ... I guess it does. – Davide Piras Commented Aug 28, 2011 at 23:16
Add a ment  | 

3 Answers 3

Reset to default 3

A few issues if I may.

I would suggest an unobtrusive approach

I would not use return false. It could have unexpected results. A quick google search will have more info.

Use preventDefault() to remove the default functionality.

https://developer.mozilla/en/DOM/event.preventDefault

Edit:

If you're unsure how to control the click event unobtrusively, addEventListener() is what you are after. You can control everything from there, including preventDefault() https://developer.mozilla/en/DOM/element.addEventListener

Not sure what you mean when you say "works in xhtml, but not in javascript."

If you want to disable a link you can just use return false to cancel the default action.

<a href="http://www.apple." onclick="return false;">Apple</a>

Update - in context of a function

<a href="/mypage.html" onclick="myFunction();">My Page</a>
<a href="/mypage.html" onclick="myFunction2(); return false;">My Page</a>

<script>
   function myFunction() {
       //do all the javascript stuff i want
       return false;
   }

   function myFunction2() {
       //do all the javascript stuff i want
   }
</script>

Don't put javascript in href. Leave the href alone. Do what you want in onclick, just make sure it returns false (so that default link action isn't executed). And remember that people opening the link in new tab/window won't get your code executed - they'll just open the link under href.

If it doesn't make sense to have a href at all, you can also have onclick on any other element, not just a.

发布评论

评论列表(0)

  1. 暂无评论