KiMoGiGi 技术文集

不在乎选择什么,而在乎坚持多久……

IT博客 首页 联系 聚合 管理
  185 Posts :: 14 Stories :: 48 Comments :: 0 Trackbacks
摘至:http://weblogs.asp.net/bleroy/archive/2007/10/18/javascript-stack-overflow.aspx

Here's one that some of you may have seen before, but I thought I'd post it to save some time to those who didn't.

Today we were trying to debug some client-side code and we needed to quickly wire the click event of a button. So we did this, without thinking too hard:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Stack overflow</title> <script type="text/javascript"> function onclick() { // do stuff } </script> </head> <body> <div> <input type="button" value="Click me" onclick="onclick();" /> </div> </body> </html>

Can you spot the stack overflow? We were so focused on the "do stuff" part that we didn't see it at first, thinking it came from there. But of course, it just comes from onclick="onclick();". When JavaScript resolves the name "onclick", it looks first on the current context before it goes up the scope chain and finds our global function (which it never does). The current context here is the input element, which happens to have an "onclick" attribute, which executes "onclick", etc. Crash.

So the valuable lesson we've learned here is to adopt a naming convention for our event handlers that can't conflict with the name of the event. I usually choose elementIdOnEventName. For example here if the input's id is button1, we'd go with button1OnClick.

posted on 2008-09-02 23:49 KiMoGiGi 阅读(486) 评论(0)  编辑 收藏 引用 所属分类: JavaScript
只有注册用户登录后才能发表评论。