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

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

    Revision

    Unobtrusive JavaScript approach was good in the PAST - especially events handler bind in HTML was considered as bad practice (mainly because onclick events run in the global scope and may cause unexpected error what was mention by YiddishNinja)

    However...

    Currently it seems that this approach is a little outdated and needs some update. If someone want to be professional frontend developper and write large and complicated apps then he need to use frameworks like Angular, Vue.js, etc... However that frameworks usually use (or allow to use) HTML-templates where event handlers are bind in html-template code directly and this is very handy, clear and effective - e.g. in angular template usually people write:

     
    

    In raw js/html the equivalent of this will be

    
    

    The difference is that in raw js onclick event is run in the global scope - but the frameworks provide encapsulation.

    So where is the problem?

    The problem is when novice programmer who always heard that html-onclick is bad and who always use btn.addEventListener("onclick", ... ) wants to use some framework with templates (addEventListener also have drawbacks - if we update DOM in dynamic way using innerHTML= (which is pretty fast) - then we loose events handlers bind in that way). Then he will face something like bad-habits or wrong-approach to framework usage - and he will use framework in very bad way - because he will focus mainly on js-part and no on template-part (and produce unclear and hard to maintain code). To change this habits he will loose a lot of time (and probably he will need some luck and teacher).

    So in my opinion, based on experience with my students, better would be for them if they use html-handlers-bind at the beginning. As I say it is true that handlers are call in global scope but a this stage students usually create small applications which are easy to control. To write bigger applications they choose some frameworks.

    So what to do?

    We can UPDATE the Unobtrusive JavaScript approach and allow bind event handlers (eventually with simple parameters) in html (but only bind handler - not put logic into onclick like in OP quesiton). So in my opinion in raw js/html this should be allowed

    
    

    or

    function popup(num,str,event) {
       let re=new RegExp(str);  
       // ... 
       event.preventDefault();
       console.log("link was clicked");
    }
    link

    But below examples should NOT be allowed

    
    
    link
    

    The reality changes, our point of view should too

提交回复
热议问题