Html onclick attribute vs script's onclick event listener [duplicate]

醉酒当歌 提交于 2019-12-25 18:15:10

问题


As a beginner I was just experimenting with various HTML elements and scripts. I then came across the HTML attribute onclick.

As I had done more of scripting before my experiments with HTML, I was wondering if there is any difference between calling the function via the DOM itself or through JS/Jquery's event listener.

E.g:-

html

<button onclick="myFunc()" id="btn1">button 1</button>

VS Script

<button id="btn2">button 2</button>

<script>
    $(document).on('click','#btn2",function(){
        //code here
    });
</script>

I would also like to know the pros and cons and which of the two is best practice.

Please do let me know if I am breaking the rules of asking questions here so I could modify/delete the question.


回答1:


I would also like to know the pros and cons and which of the two is best practice.

Pros of "VS Script":

  • elements can be added without having to add click handlers, even after function has been declared
  • A single callback function can handle clicks (or other events) on various elements and then delegate the action to various functions...
  • Using an onClick or similar attribute is a mix of JS within the HTML - this goes against the Separation of Concerns principle. With the "VS Script" the logic is separate from the markup.
  • can avoid memory-leaks
  • lends itself better to event delegation
  • Code sanitizers may complain about inline scripts in attributes like onclick, onmouseout, etc.

Cons of "VS Script":

  • Elements added to the DOM after the click handler has been registered won't trigger the click handler (see this answer for more details).
  • Support from older browsers may make achieving this more complex (e.g. addEventListener before IE 9... though if you are using a library like jQuery (like you mentioned), then this is likely handled for you...
  • More work may need to be done to get attributes of the element for which the event occurred on

For a more detailed explanation, see this answer.



来源:https://stackoverflow.com/questions/42819916/html-onclick-attribute-vs-scripts-onclick-event-listener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!