How bad it is - Inline js calls with external handlers definition VS totally external js
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 开发者_Python百科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?
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.
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.
精彩评论