Why is using onClick() in HTML a bad practice?

前端 未结 10 2426
我寻月下人不归
我寻月下人不归 2020-11-21 05:07

I have heard many times that using JavaScript events, such as onClick(), in HTML is a bad practice, because it\'s not good for semantics. I would like to know w

10条回答
  •  半阙折子戏
    2020-11-21 05:57

    There are a few reasons:

    1. I find it aids maintenence to separate markup, i.e. the HTML and client-side scripts. For example, jQuery makes it easy to add event handlers programatically.

    2. The example you give would be broken in any user agent that doesn't support javascript, or has javascript turned off. The concept of progressive enhancement would encourage a simple hyperlink to /map/ for user agents without javascript, then adding a click handler prgramatically for user agents that support javascript.

    For example:

    Markup:

    link
    

    Javascript:

    $(document).ready(function(){
    
        $("#example").click(function(){
            popup('/map/', 300, 300, 'map');
            return false;
        });
    
    })
    

提交回复
热议问题