Using "return false;" in onclick Event in JavaScript

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.   


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. 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值