Why are inline event handler attributes a bad idea in modern semantic HTML?

后端 未结 3 468
长发绾君心
长发绾君心 2020-11-22 12:17

Is inline event handlers considered a bad practice?

For example:

If so, what are t

3条回答
  •  情话喂你
    2020-11-22 13:13

    It's a bad idea because...

    1) For a long time now there has been a sensible emphasis on a clear split between content, style and script. Muddying your HTML with JS is not consistent with this.

    2) More importantly, you get much less control over your events. Specifically:

    • you can bind only one event of each kind with DOM-zero events (which is what the inline ones are), so you can't have two click event handlers

    • if an event is specified inline, the JS is specified as a string (attribute values are always strings) and evaluated when the event fires. Evaluation is evil.

    • you are faced with having to reference named functions. This is not always ideal (event handlers normally take anonymous functions) and has implications on the function needing to be global

    In short, handle events centrally via the dedicated addEventListener API, or via jQuery or something.

提交回复
热议问题