JavaScript 'onclick' event 'return' keyword functionality

前端 未结 3 510
情深已故
情深已故 2020-12-04 11:18

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



        
相关标签:
3条回答
  • 2020-12-04 11:51

    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 returning nothing.

    0 讨论(0)
  • 2020-12-04 12:00

    Returning false from the function, will abort the effect of the checking. Because the native of functions that written hardcoded into html properties (it became some new local function), writing the html without the word "return" will just run the function, and lose its returning value, as if you've wrote:

    function doAlert() {
       if(some_condition)
         return false;
       else
         return true;
    }
    function some_local_function() {
       doAlert();
    }
    

    Function some_local_function won't return any value, although doAlert returns.

    When you write "return", it's like you wrote the second function like this:

    function some_local_function() {
       return doAlert();
    }
    

    which preserves the returning value of doAlert, whatever it will be. If it's true - the action will perform (the checkbox will be checked) - otherwise - it will cancel.

    You can see live expamle here: http://jsfiddle.net/RaBfM/1/

    0 讨论(0)
  • 2020-12-04 12:10

    adding return to a function(), it disables the default behaviour of the browser, it disables the job of submit. Means it will keep you on the same page if the function returns false and you can fill up the value into the field again.

    If you do not use return with the function() then submit function will perform its job, it will redirect to the next specified page, without caring about the returned result whether it was true or false.

    0 讨论(0)
提交回复
热议问题