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

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

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

Click here !
16条回答
  •  你的背包
    2020-11-21 23:34

    I have this link on my HTML-page:

     click here 
    

    The function setBodyHtml() is defined as:

    function setBodyHtml (s)
    { document.body.innerHTML = s;
    }
    

    When I click the link the link disappears and the text shown in the browser changes to "new content".

    But if I remove the "false" from my link, clicking the link does (seemingly) nothing. Why is that?

    It is because if I don't return false the default behavior of clicking the link and displaying its target-page happens, is not canceled. BUT, here the href of the hyperlink is "" so it links back to the SAME current page. So the page is effectively just refreshed and seemingly nothing happens.

    In the background the function setBodyHtml() still does get executed. It assigns its argument to body.innerHTML. But because the page is immediately refreshed/reloaded the modified body-content does not stay visible for more than a few milliseconds perhaps, so I will not see it.

    This example shows why it is sometimes USEFUL to use "return false".

    I do want to assign SOME href to the link, so that it shows as a link, as underlined text. But I don't want the click to the link to effectively just reload the page. I want that default navigation=behavior to be canceled and whatever side-effects are caused by calling my function to take and stay in effect. Therefore I must "return false".

    The example above is something you would quickly try out during development. For production you would more likely assign a click-handler in JavaScript and call preventDefault() instead. But for a quick try-it-out the "return false" above does the trick.

提交回复
热议问题