admin管理员组文章数量:1327470
I would like to know why it's better to use observers rather than adding the action directly into the onclick="".
eg.
$('mybutton').observe('click', respondToClick);
vs
<a href="#" onclic="respondToClick()">button</a>
Thanks
I would like to know why it's better to use observers rather than adding the action directly into the onclick="".
eg.
$('mybutton').observe('click', respondToClick);
vs
<a href="#" onclic="respondToClick()">button</a>
Thanks
Share Improve this question edited Dec 28, 2011 at 11:27 Rob W 349k87 gold badges807 silver badges682 bronze badges asked Mar 4, 2011 at 12:02 RochRoch 22.1k29 gold badges79 silver badges123 bronze badges4 Answers
Reset to default 5This is a fairly mon question so I'll refer you to a quality article on quirksmode that answers this question and other question you may have about event handling.
Here is an excerpt:
<a href="somewhere.html" onclick="alert('I\'ve been clicked!')">
It is very important to realize that this ancient way of event handling was de facto standardized by Netscape. All other browsers, including Explorer, had to conform to the way Netscape 2 and 3 handled events if they wanted JavaScript to work. Therefore these ancient events and event handlers work in all JavaScript browsers.
Have fun reading.
Generally most people would suggest to keep your javascript seperate from your html, allowing for faster html page rendering. You'll have to be more careful with the first though, due to cross browser inpatabilities with code
The biggest reason is that observe
lets you register and unregister multiple observers via your JavaScript code, whereas assigning to onclick
is a lot less flexible.
The three main reasons for me are as such:
- I like to keep my HTML templates abstract. Having javascript code embedded in the markup means my code re-use for that template code be slightly hampered. You would need to be sure you can include the script file in the head of the document. (For certain CMS systems, this can be a bit of a hassle to configure)
- How would you remove that event handler?
el.onclick = null;
won't always work. IE has a way of allowing memory leaks. - Applying behaviors via class names or id's provides much greater re-usability for your javascript code than sticking in an onclick handler.
本文标签: javascriptonClick Vs ObserverStack Overflow
版权声明:本文标题:javascript - onClick Vs Observer - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742208393a2433245.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论