JavaScript function in href vs. onclick

后端 未结 15 1986
栀梦
栀梦 2020-11-22 07:17

I want to run a simple JavaScript function on a click without any redirection.

Is there any difference or benefit between putting the JavaScript call in the hr

15条回答
  •  伪装坚强ぢ
    2020-11-22 08:01

    The top answer is a very bad practice, one should never ever link to an empty hash as it can create problems down the road.

    Best is to bind an event handler to the element as numerous other people have stated, however, do stuff works perfectly in every modern browser, and I use it extensively when rendering templates to avoid having to rebind for each instance. In some cases, this approach offers better performance. YMMV

    Another interesting tid-bit....

    onclick & href have different behaviors when calling javascript directly.

    onclick will pass this context correctly, whereas href won't, or in other words no context won't work, whereas no context will.

    Yes, I omitted the href. While that doesn't follow the spec, it will work in all browsers, although, ideally it should include a href="javascript:void(0);" for good measure

提交回复
热议问题