开发者

an event-handing question in javascript

开发者 https://www.devze.com 2023-02-21 21:56 出处:网络
If I define a function like this: function doSomething() { this.style.color = \'#cc0000\'; } Do element.attachEvent(\'onclick\',doSomething)

If I define a function like this:

function doSomething()
{
    this.style.color = '#cc0000';
}

Do

element.attachEvent('onclick',doSomething)

and

element.addEventListener('click',doSomething,false)

get the same result? And why?Thanks a l开发者_高级运维ot.


Yes, but in different browsers.

  • attachEvent is the method you have to use in IE.

  • addEventListener is available in all other browsers (Firefox, Chrome, Safari, Opera, etc). It is the W3C standard. IE9 tries to be more compatible with W3C and supports it too.

I suggest to read Advanced event registration models which explains the browser differences quite well.

You should also read the other articles about events on quirksmode.org. They will give you a good in event handling in general.


Pretty much, addEventListener is the W3C way of adding events and supported by most browsers, while attachEvent is an IE thing and supported mainly by them. Read more.

0

精彩评论

暂无评论...
验证码 换一张
取 消