Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

html - JavaScript 'onclick' event 'return' keyword functionality

I am really new to javascript, and stumbled upon the return keyword. Basically, what is the difference in terms of these 2 statements?

<input type="checkbox" onclick="doAlert()" />

vs

<input type="checkbox" onclick="return doAlert();" />

Essentially, both returned the same results and called the function, but is there more to it? Any help greatly appreciated :). Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Some html elements have JS events that behave differently when true/false is returned. For instance:

<input type='submit' value='Click Me' onSubmit='ValidateForm();'>

...vs...

<input type='submit' value='Click Me' onSubmit='return ValidateForm();'>

In the second instance, if the ValidateForm function returned false the form will not submit, in the first even if the function returns false the form will still submit.

I think this scenario, you can see the different between using the return keyword and not.

UPDATED To simplify, if you use the return keyword you are passing a value back to the function that called the onsubmit. Without it, you are simply calling the function that you name in the event handler and do not return anything.

UPDATE 2021-01-21 This functionality also work for the onclick method on html anchors / links (a):

Sample Usage:

<a href="#never-used" onclick="alert('click clack'); return false;" > 

Click Me


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...