使用 jQuery 的 onclick 和 onclick 属性有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/398760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:05:19  来源:igfitidea点击:

What's the difference between using jQuery's onclick and the onclick attribute?

jquery

提问by Kevin Pang

What's the difference between the following two pieces of HTML (apologies if there are any typos as I'm typing this freehand)?

以下两段 HTML 之间有什么区别(如果我徒手打字时有任何错别字,请见谅)?

Using jQuery:

使用jQuery:

<script type="text/javascript">
    $(document).ready(function() {
        $("#clickme").click(function() {
            alert("clicked!");
        });
    });
</script>

<a id="clickme" href="javascript:void(0);">click me</a>

Not using jQuery:

不使用 jQuery:

<a id="clickme" href="javascript:void(0);" onclick="alert('clicked!');">click me</a>

回答by Adam Bellaire

One big difference is that jQuery's events are handled in a registry which is parsed on the click event. Crucially, this means that you are permitted to assign multiple callbacks, and have them triggered in the order in which they were registered:

一个很大的区别是 jQuery 的事件是在一个注册表中处理的,这个注册表是在点击事件上解析的。至关重要的是,这意味着您可以分配多个回调,并按照它们的注册顺序触发它们:

<script type="text/javascript">
    $(document).ready(function() {
        $("#clickme").click(function() {
            alert("clicked!");
        });
        $("#clickme").click(function() {
            alert("I concur, clicked!");
        });
    });
</script>

They will both be invoked on the clickevent, in that order. The "real" onClickevent is overridden by jQuery's registry-driven system. In the vanilla document structure, without a system like jQuery in place, there can only be one onClickevent.

它们都将按click该顺序在事件中被调用。“真实”onClick事件被 jQuery 的注册表驱动系统覆盖。在普通的文档结构中,如果没有像 jQuery 这样的系统,就只能有一个onClick事件。

回答by palehorse

It is also a cleaner separation of UI code (the HTML) and the logic code (the JavaScript). It makes reading each a bit easier.

它也是 UI 代码(HTML)和逻辑代码(JavaScript)的更清晰的分离。它使阅读每一个都更容易。

回答by orip

One of the differences is that adding handlers with jQuery's clickdoesn't remove previous handlers.

区别之一是使用 jQuery 添加处理程序click不会删除以前的处理程序。