What's the effect of adding 'return false' to a click event listener?

前端 未结 16 1976
南旧
南旧 2020-11-21 22:59

Many times I\'ve seen links like these in HTML pages:

Click here !
16条回答
  •  半阙折子戏
    2020-11-21 23:36

    I am surprised that no one mentioned onmousedown instead of onclick. The

    onclick='return false'

    does not catch the browser's default behaviour resulting in (sometimes unwanted) text selection occurring for mousedown but

    onmousedown='return false'

    does.

    In other words, when I click on a button, its text sometimes becomes accidentally selected changing the look of the button, that may be unwanted. That is the default behaviour that we are trying to prevent here. However, the mousedown event is registered before click, so if you only prevent that behaviour inside your click handler, it will not affect the unwanted selection arising from the mousedown event. So the text still gets selected. However, preventing default for the mousedown event will do the job.

    See also event.preventDefault() vs. return false

提交回复
热议问题