开发者

What the difference between returning or not? [duplicate]

开发者 https://www.devze.com 2023-03-29 09:32 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicates: What's the effect of adding 'return false' to an onclick event?
This question already has answers here: Closed 11 years ago.

Possible Duplicates:

What's the effect of adding 'return false' to an onclick event?

When and why to 'return false' in javascript?

I mean, if I have this function :

 function openMask() {
     alert("enter");
 }
开发者_运维技巧

is it better call it as :

 <a href="javascript:void(0);" onclick="openMask()">Link</a>

or :

 <a href="javascript:void(0);" onclick="openMask(); return false;">Link</a>

??? I'm really curious about it! Never understood the difference...


In a DOM event handler (such as onclick), returning true means "continue with the event", and returning false means "don't".

In this case, it's not entirely meaningful because your href is already javascript:void(0) (which won't do anything).

Note, though, that javascript: URIs should really be avoided, and that this isn't very helpful for non-Javascript users, so you should provide a fallback page, and then the return false becomes more meaningful:

JS:

function openMask() {
   alert("enter");
   return false; 
}

HTML:

<a href="fallbackpage.html" onclick="return openMask();">Link</a>


The best would be to use:

 <a href="/page/with/opened/mask" onclick="openMask(); return false;">Link</a>

So users without JavaScript (including Google Bot) can use your site.


return false causes the browser to ignore the href. In your specific example it changes nothing since the href does nothing, but it would matter if you had something like href='#'


return false   

means prevent the default behavior of an event. in your example, that's prevent the browser to open the url of link

0

精彩评论

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