Proper way for links to execute javascript code

假如想象 提交于 2019-12-01 04:27:14

You make the page not jump and use an "a" tag with an href and method 4 using preventDefault.

<a id="executeMyCodeLink" href="#">execute</a>
<script>
  $('#executeMyCodeLink').click(function(event) {
    event.preventDefault();
    myCode();
  });
</script>

It's important to include an href because links won't style properly and your html won't validate otherwise.

I prefer method 4, but with two differences:

  • Move the script to a separate file. Unobtrusive JavaScript is happy JavaScript.
  • Use the a tag, link to # and return false.

<a href="#_"> works too, that way you don't need a return false. (Any non-existent anchor will work really).

Also, method 4 only works if you use jQuery. Most of my websites only have one or two small javascript effects, I'm not loading jQuery for that.

Using jquery is an unobtrusive way to handle javascript calls. So I would say method 4. You can also just do:

$(a#linkId).click(...);

I prefer method 4, too.

Binding events to dom objects seperately is a more elegant way and I think that's a good programming habit.

I like method 4 as well. Whenever possible i try to not put anything directly in the even attributes or to write js directly into the href. I do this because in most cases ill actually put a non-js url as the href so it degrades for non-js enabled browsers. The second reson is i dont like to pollute elements with cruft :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!