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

前端 未结 10 2197
我寻月下人不归
我寻月下人不归 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:34

    If you are using jQuery then:

    HTML:

     link
    

    JS:

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

    This has the benefit of still working without JS, or if the user middle clicks the link.

    It also means that I could handle generic popups by rewriting again to:

    HTML:

     link
    

    JS:

    $(document).ready(function() {
        $(".popup").click(function(){
            popup($(this).attr("href"), 300, 300, 'map');
            return false;
        });
    });
    

    This would let you add a popup to any link by just giving it the popup class.

    This idea could be extended even further like so:

    HTML:

     link
    

    JS:

    $(document).ready(function() {
        $(".popup").click(function(){
            popup($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');
            return false;
        });
    });
    

    I can now use the same bit of code for lots of popups on my whole site without having to write loads of onclick stuff! Yay for reusability!

    It also means that if later on I decide that popups are bad practice, (which they are!) and that I want to replace them with a lightbox style modal window, I can change:

    popup($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');
    

    to

    myAmazingModalWindow($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');
    

    and all my popups on my whole site are now working totally differently. I could even do feature detection to decide what to do on a popup, or store a users preference to allow them or not. With the inline onclick, this requires a huge copy and pasting effort.

提交回复
热议问题