简体   繁体   中英

syntax difference in javascript function calling?

What is the difference between:

<div onclick="return function()"></div>

vs

<div onclick="function()"></div> 

They seem to be doing the same thing for me and I am not sure which one to use.

Take for example <form onsubmit="return validate();">... The submit will be cancelled if validate() returns false.

With <form onsubmit="validate();">... The submit will continue regardless of the return value of validate().

Explanation in words..

One will return the value to the element which the attribute resides in, the other will not.

When you use return function () the default click-method of the element will only be executed if function () evaluates to a value that implicitly is converted to true .

If it yields false the evaluation of the click-event will halt after running the onclick -property.


In case of onclick="function ()" the default click-propery of the element will always be executed, no matter what the function returns.


Example snippets with detailed information of what is happening..

function some_func () { return false; }

<a href="http://google.com" onclick="return some_func()">
  link #1
</a> <!-- user will never end up at google -->

if javascript is enabled in the browser, of course..

<a href="http://google.com" onclick="some_func()">
  link #1
</a> <!-- user will always end up at google -->

There is a difference, if you write return, it will check if the return is true or false and will only take action if return is true. otherwise it will just process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM