为什么JSLint限制HTML事件处理程序的使用? [英] Why does JSLint restrict the use of HTML event handlers?

查看:73
本文介绍了为什么JSLint限制HTML事件处理程序的使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JSLint上使用默认值"Good Parts",则不允许使用HTML事件处理程序(例如onclick).

Using the "Good Parts" defaults on JSLint, the use of HTML event handlers (such as onclick) is not allowed.

这背后的逻辑是什么?他们应该避免哪些不利因素?

What is the logic behind this? What is bad about them that should be avoided?

推荐答案

在JSLint上使用默认值"Good Parts",则不允许使用HTML事件处理程序(例如onclick).

Using the "Good Parts" defaults on JSLint, the use of HTML event handlers (such as onclick) is not allowed.

标记了在实际标记中使用事件处理程序,是的:

The use of event handlers in the actual markup is flagged, yes:

<div onclick="...">

通常认为这是不好的做法.将脚本行为混入标记中很难阅读和管理.在实际的脚本中更容易将所有脚本保持在一起,因此您不必深入研究标记就可以找到正在调用的脚本钩子.

This is generally considered bad practice. Mixing scripting behaviour into markup is hard to read and manage; easier to keep all your scripting together, in an actual script, so you don't have to delve into your markup to find what scripting hooks are being called.

此外,通过将脚本代码放在需要HTML编码的上下文中,您还增加了一层避免混淆的功能.您最终会说出讨厌的话,例如:

Also, by putting your script code in a context where it needs HTML-encoding, you are adding an extra layer of escaping confusion. You end up saying nasty stuff like:

<div onclick="if (a&lt;b) this.innerHTML= &quot;I said \&quot;Hello &amp;amp; welcome!\&quot;&quot;">

自然很难正确地进行编码,而且如果您要处理动态值,则错误的编码组合会导致脚本注入(XSS)问题.

naturally it's difficult to get this encoding right, and if you're dealing with dynamic values an incorrect combination of encodings leaves you with a script-injection (XSS) problem.

在独立脚本中相同:

somediv.onclick= function() {
    if (a<b)
        this.innerHTML= "I said \"Hello &amp; welcome!\"";
};

是一种转义级别的清除器.

is one escaping level clearer.

JSLint没有抱怨这种用法.尽管有人会认为使用侦听器会更好,因为您可以将多个侦听器添加到一个事件中,但这更是一个重量级的解决方案,因为您必须解决IE< 9的attachEvent而不是addEventListener的问题,并可能为较旧的版本提供一些东西不支持的浏览器.

JSLint does not complain about this usage. Whilst some would argue that using listeners is better as you can add multiple listeners to an event, that's more of a heavyweight solution, as you have to work around IE<9's attachEvent instead of addEventListener, and perhaps provide something for older browsers that support neither.

这篇关于为什么JSLint限制HTML事件处理程序的使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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