JavasScript事件处理最佳实践? [英] JavasScript event handling best practice?

查看:104
本文介绍了JavasScript事件处理最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义JavaScript调用时,如下所示:

When defining a JavaScript call, like so:

<input type="button" onclick="someJavaScriptFunction" />

写实际通话的最佳方式是什么?我见过很多方法:

What is the best way to write the actual call? I've seen numerous method:

javascript:someJavascriptFunction();

justSomeJavaScriptFunction();

withoutTheSemicolon()

对任何方法有任何好处或警告吗?我意识到在某些情况下使用 addEventListener 会更灵活。

Are there any benefits or caveats to any of the methods? I realize that using addEventListener is more flexible in certain cases.

推荐答案

如果您想要最佳练习,请将标记与脚本内容分开。在脚本元素中分配事件处理程序。正如你所说,使用 addEventListener 是这样做的一种方法,尽管如果你想要你也必须使用 attachEvent 支持版本9之前的Internet Explorer版本。

If you want best practice, separate markup from script content. Assign your event handlers in script elements. As you say, using addEventListener is one way of doing this, although you have to use attachEvent as well if you want to support versions of Internet Explorer before version 9.

然而,分配 onevent 属性是完全有效的。例如:

It's perfectly valid, however, to assign onevent properties. For instance:

<script>
    window.onload = function() {
        document.getElementById('yourID').onclick = function() {
           alert('element clicked');
        };
    };
</script>

如果您只有几件物品,这可能适合您的目的。

This may well suit your purpose adequately, if you only have a few items.

这篇关于JavasScript事件处理最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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