开发者

Why is return false and return true used after this inline event-handler?

<button onclick="alert('Hello'); return false;">Hello</button>

What is the return false part supposed to do? Also, what would return true do if it were开发者_运维技巧 there?


The return false will disregard default behavior for the onclick event. So, for example, if you had a link:

<a href="http://stackoverflow.com" onclick="alert('Hello'); return false">Link<a>

when the user clicks on the link they'd get a popup but wouldn't actually go the target of the link.


The default button type is submit, so <button> is the same as <button type="submit"> (except on IE). The return false stops the default button action so it will stop form submission from happening.

You can avoid that by defining the button type explicitly

<button type="button" onclick="alert('Hello');">Hello</button>


It depends on the context.

For example return true|false on a submit button either does or does not submit the form which you can use for form validation, i.e. return false if the validation fails and prevent the form from submitting.

In many cases it will acheive nothing for example the button in your code example to my knowledge does nothing with the retirn value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜