最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - onClick Vs Observer - Stack Overflow

programmeradmin3浏览0评论

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 badges
Add a ment  | 

4 Answers 4

Reset to default 5

This 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:

  1. 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)
  2. How would you remove that event handler? el.onclick = null; won't always work. IE has a way of allowing memory leaks.
  3. Applying behaviors via class names or id's provides much greater re-usability for your javascript code than sticking in an onclick handler.
发布评论

评论列表(0)

  1. 暂无评论