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

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

问题描述

内部事件处理程序被认为是不好的做法?



例如:< button onclick = someFunction()>点击我!< ; / button>



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

解决方案

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



1)很久以前,在内容,样式和脚本之间有明确的分割。用JS粘贴你的HTML与这不一致。



2)更重要的是,你对事件的控制要少得多。具体来说:




  • 您可以仅使用DOM-zero事件绑定每种事件(这是内联的事件) ,所以如果一个事件是内联的,你不能有两个点击事件处理程序


  • JS被指定为字符串(属性值总是字符串),并在事件触发时进行评估。评估是邪恶的。


  • 你面对必须引用命名函数。这并不总是理想的(事件处理程序通常采用匿名函数),并且对需要全局的函数有影响。




简而言之,通过专门的 addEventListener API,或通过jQuery或某些东西集中处理事件。


Is inline event handlers considered a bad practice?

For example: <button onclick=someFunction()>Click me!</button>

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

解决方案

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.

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

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