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

前端 未结 3 472
温柔的废话
温柔的废话 2020-12-12 17:14

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

Using jQuery:



        
相关标签:
3条回答
  • 2020-12-12 17:56

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

    0 讨论(0)
  • 2020-12-12 17:57

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

    0 讨论(0)
  • 2020-12-12 17:58

    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:

    <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 click event, in that order. The "real" onClick event 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 onClick event.

    0 讨论(0)
提交回复
热议问题