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

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

问题描述

内联事件处理程序是否被认为是一种不好的做法?

Is inline event handlers considered a bad practice?

例如:

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

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

推荐答案

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

It's a bad idea because...

  1. 最佳实践建议明确划分内容、风格和脚本.使用内联 JavaScript(或 CSS)混淆您的 HTML 与此不一致.

  1. Best practice suggests a clear split between content, style and script. Muddying your HTML with inline JavaScript (or CSS) is not consistent with this.

您只能使用 on* 样式的 events 绑定每种类型的一个事件,例如,您不能有两个 onclick 事件处理程序.

You can bind only one event of each kind with on*-style events , so you can't have two onclick event handlers, for example.

如果内联指定事件,则 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 globally accessible

您的内容安全策略 (CSP) 必须(不明智地)扩展以允许评估的内联 JavaScript.

Your content security policy (CSP) will have to be (unwisely) expanded to allow evaluated inline JavaScript.

简而言之,通过专用的 addEventListener API 或通过 jQuery 或其他方式集中处理事件.

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

[2021 编辑]

如今,响应式框架在某种程度上扭转了这一趋势;反应式框架中的事件通常被指定为属性,例如在 Vue 中:

These days, reactive frameworks have somewhat reversed this trend; events in reactive frameworks are normally specified as attributes e.g. in Vue:

<p v-on:click=foo>Hello</p>

...其中 foo 是当前组件的数据对象的方法.

...where foo is a method of the current component's data object.

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

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