How bad it is - Inline js calls with external handlers definition VS totally external js

寵の児 提交于 2019-12-19 10:22:19

问题


I run into following code in my project:

html:

<input type="button" id="addmore" value="Add more" onclick="add_table(this)"/>

js:

function add_table(elem){
    var current_id = jQuery("table.t1:last").attr("id");

First I thought that this code is wrong and I must rewrite it to external code, i.e.

jQuery('#addmore)'.click(function add_table(elem){
    var current_id = jQuery("table.t1:last").attr("id");

But then I looked at it again and found that this html is more readable - I see which functions binds to which elements already in html, and I don't need to search it in js.

Of course it not encapsulated inside

jQuery(document).ready( 

so it will not work under some circumstances

So question: how bad this code is?


回答1:


It's a question re-usability and personal taste. Inline code is more readable for very simple things like your example, but of course you are relying on add_table() being a global function - if you have hundreds of elements with different click handlers, you could end up with hundreds of functions/variables polluting the global namespace. And that's bad! :)

In terms of re-usability, I find it better to code in distinct components that abstract functionality and can be called upon whenever needed - all within a defined (non-global) namespace.

jQuery('#addmore)'.click(function add_table(elem) {
    var current_id = jQuery("table.t1:last").attr("id");
}

The code above gives a good separation of concerns - meaning the semantic information (HTML) is oblivious to the behavioural information (Javascript), which again helps create cleaner, more manageable code.




回答2:


Depending on the size of your site (and level of traffic) there might be a bandwidth issue. i.e. onclick="add_table(this)" adds 24 bytes of data to a download. This could be put in a cached JavaScript page which only gets downloaded once, rather than for each request. If you have lots of pages with extra code in them an you have a lot of traffic it may make a noticeable bandwidth difference.



来源:https://stackoverflow.com/questions/6015611/how-bad-it-is-inline-js-calls-with-external-handlers-definition-vs-totally-ext

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