开发者

Javascript - return keyword in Form vs Function

开发者 https://www.devze.com 2023-02-11 11:28 出处:网络
How does a return work in a Form vs a function? I know you can return false 开发者_JAVA百科in a function and it will stop the flow of the program,great if you want to cancel a postback.Why would I ha

How does a return work in a Form vs a function?

I know you can return false 开发者_JAVA百科in a function and it will stop the flow of the program, great if you want to cancel a postback. Why would I have a return in a Form as well?

Author snippet from beginning javascript book by Christian Heilmann:

<form action="whatever" method="post" onsubmit="return checkSearch();">

function checkSearch()
{
  alert ('foo');
  return false;
}


When returning false from a function that handles an event, it will (generally) stop the default action. So in the case of your example, if the onSubmit function returns false, the form will not submit (the default action).

Similarly, if you return false from an onClick event, the default action (following the link) is halted. If you return true, the browser will attempt to follow the link after your script executes.


Look at this this way:

function onsubmit(){
  return checkSearch();
}


Why would I have a return in a Form as well?

Because that (returning false from the event handler) is what stops the flow of the program (in this case, further processing of the event). The return false from the function itself has no effect without that!

0

精彩评论

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

关注公众号