内联处理程序是如何处理的?

发布于 2024-11-05 00:21:04 字数 267 浏览 4 评论 0原文

我怀疑内联处理程序已被评估,但找不到任何相关信息。出于好奇:有谁知道这样的处理程序是如何处理的?为了清楚起见,我的意思是内联处理程序,例如:

<a href="#" onclick="doSomethingReallyCunning()">...</a>
<input type="checkbox" onmouseover="this.checked=!this.checked;this.blur()"/>

等。

I have the suspicion that inline handlers are evalled, but can't find any information on that. Out of curiosity then: does anyone knows how such handlers are processed? For clarity, I mean inline handlers like:

<a href="#" onclick="doSomethingReallyCunning()">...</a>
<input type="checkbox" onmouseover="this.checked=!this.checked;this.blur()"/>

etc.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

感性 2024-11-12 00:21:04

在内部,内联事件属性是通过创建一个匿名包装函数来处理的,如下所示:

element.onclick = new Function("event", onclickAttribute);
// etc.

这意味着属性的内容会被evaled,但仅当元素被插入到 DOM 中时(此后该函数被以内存中解析的形式,就像其他事件处理程序一样)。这意味着它不会比您自己的单独 JavaScript 代码中分配的事件处理程序消耗更多的内存和时间。即使每次事件发生时都必须解析代码,也不会产生如此大的差异以至于用户会注意到它。

然而,避免使用内联事件属性有一个很好的理由:保持表示和逻辑彼此分离,这可以提高可读性和可维护性。另一个优点是使用压缩器不那么痛苦,因为 JavaScript 文件中的函数名称可能会根据压缩器的设置和智能而更改,但不会在标记中更改(解决此问题的方法是在定义时使用方括号表示法)代码中的这些函数(例如 window['doSomethingReallyCunning'] = function (...) {...),因此函数名称将保持不变,但是,如果有的话,这当然不是一个巧妙的解决方案;有一个更好的可用)。如果您仅通过直接引用函数在代码中分配事件处理程序,则该函数名称的所有实例都会更改(当然,setTimeoutsetInterval 的参数也是如此)。

Internally, inline event attributes are processed by creating an anonymous wrapper function like this:

element.onclick = new Function("event", onclickAttribute);
// etc.

This means that the contents of the attribute are evaled but only when the element is inserted into the DOM (after this the function is in a parsed form in memory, just like other event handlers). This means that it will not consume much more memory and time than event handlers assigned in your own, separate JavaScript code. And even if the code had to be parsed every time the event occurs, it wouldn't make such a big difference that a user will notice it.

However, there's a good reason to stay away from using inline event attributes: keeping presentation and logic separate from each other, which improves readability and maintainability. Another advantage is that using minifiers is less painful, as those function names in your JavaScript files may be changed depending on the minifier's settings and intelligence, but not in your markup (a work around to this issue is to use the square bracket notation when defining those functions in your code (like window['doSomethingReallyCunning'] = function (…) {…), so the function name will be kept intact; however, this is of course not a neat solution if there's a much better one available). If you only assign event handlers in your code by directly referencing functions, all instances of that function's name are changed (of course, the same is true for parameters to setTimeout and setInterval).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文