开发者

an event-handing question in javascript

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜