简体   繁体   中英

javascript event handling

I have a query. I use to call a function on javascript event in 2 ways.

  1. Inside HTML tag like:

     <div id='someid' onmouseover='callFunc()'>Some Text</div>
  2. Outside tag like in script tag/ external file:

     document.getElementById('someid').onmouseover=function(){ alert('hi'); }

Now I think both serve the same purpose, then is there any difference between the two ways? Which one is better? What are the pros and cons of both? Second, is there any other way to call this function?

Both are bad. You want addEventListener . A library like jQuery will make this much easier, like so:

$('#someid').mouseover(function() { alert('hi') });

Putting JavaScript inline in HTML is never a good idea; it's hard to write (you have to worry about escaping) and hard to maintain.

Assigning directly to on* is ok, but then you can't have multiple event handlers for the same event on the same element. If some other code tries to add a handler later, it'll wipe out your handler.

It's much better to separate your code from your html.

When all your code is well organized in one section or better yet a separate file, it's much easier to maintain your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM