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" οnclick="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"
οnclick="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"
οnclick="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"
οnclick="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.