为什么内联事件处理程序属性在现代语义HTML中是个坏主意? [英] Why are inline event handler attributes a bad idea in modern semantic HTML?

查看:82
本文介绍了为什么内联事件处理程序属性在现代语义HTML中是个坏主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

内联事件处理程序是否被视为不良习惯?

Is inline event handlers considered a bad practice?

例如:<button onclick=someFunction()>Click me!</button>

如果是这样,使用内联事件处理程序的缺点是什么?

If so, what are the disadvantages of using inline event handlers?

推荐答案

这是个坏主意,因为...

It's a bad idea because...

1)很长一段时间以来,人们一直在明智地强调内容,样式和脚本之间的清晰区分.用JS弄乱HTML与此不符.

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)更重要的是,您对事件的控制要少得多.具体来说:

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

  • 您只能将每种事件与DOM-零事件(即内联事件)绑定在一起,因此您不能有两个click事件处理程序

如果内联指定事件,则将JS指定为字符串(属性值始终为字符串),并在事件触发时进行评估.评价是邪恶的.

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

简而言之,可通过专用的addEventListener API或通过jQuery等工具集中处理事件.

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

这篇关于为什么内联事件处理程序属性在现代语义HTML中是个坏主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆