您的位置:首页 > Web前端 > JavaScript

Using "return false;" in onclick Event in JavaScript

2014-06-27 22:05 573 查看
In my job, I have read the html files of many static webpages. It seems that people like to use the onclick JavaScript event with the window.open() JavaScript method to create links that open web content in new pages. The syntax is usually
like this:

<a href="http://www.csdn.net" onclick="window.open(this.href); return false;" title="CSDN">CSDN</a>


Aftering seeing this so many times, I began to raise a question : what is the function of the "return false;" statement? I design some experiments and soon found out the answer.

<!--two windows would be opened-->
<a href="http://www.google.com.hk" target="_blank"
onclick="window.open('http://www.csdn.net')">This is a link</a>

<!--return false to prevent default behaviour-->
<a href="http://www.google.com.hk" target="_blank"
onclick="window.open('http://www.csdn.net'); return false;">This is a link</a>


This example above is straight forward. I compared the two links, one without
"return false;" and one with it. The one without it would open two new windows when clicked as both the a link and the onclick event are triggered. The one with it would only open a window for CSDN. Why do they behave differently? It is because
the"return false;" statement prevents the default behaviour of the browser, that is, opening a new window for Google.

You may think that the "return false;" statement is not so useful in the example above. Actually, we can do some simple interaction using the mechanism. For example, in the code below, the onclick event has the confirm() JavaScript method
as its event handler. The confirm() method returns true when we click "OK" in the dialog box and false otherwise. Therefore, we can use the confirm() method to control whether the webpage in the a link would be opened.

<a href="http://www.google.com.hk" target="_blank"
onclick="return confirm('Are you sure?');">This is a link</a>


However, don't abuse the use of "return false;" in your webpages. It may be confusing and difficult to maintain sometimes. In simple inline event handler like the examples above, it is acceptable to use it. However, using it in complicated functions may
cause unpredictable behaviours. I may write posts about it later to analyse the issue.   

Do you find it interesting? Share it with your friends if you like the post. I will try to dig out more secrets of JavaScript in the near future. 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息