问题描述
我在我的项目中遇到以下代码:
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");
然后我再次查看它并发现这个html更具可读性 - 我看到哪些函数绑定到html中的哪些元素,我不需要在js中搜索它。
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.
当然不是封装在里面
jQuery(document).ready(
因此在某些情况下不起作用
so it will not work under some circumstances
所以问:这段代码有多糟糕?
So question: how bad this code is?
推荐答案
这是一个可重用性和个人品味的问题。内联代码对于像你的例子这样非常简单的事情更具可读性,但当然你依赖于 add_table()
作为一个全局函数 - 如果你有数百个elem如果有不同的点击处理程序,最终可能会有数百个函数/变量污染全局命名空间。那太糟糕了! :)
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! :)
在可重用性方面,我发现在抽象功能的不同组件中编码更好,并且可以在需要时调用 - 所有这些都在定义的内部(非-global)namespace。
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");
}
上面的代码提供了一个很好的 - 意思是语义信息(HTML)没有注意到行为信息(Javascript),这有助于创建更清晰,更易于管理的代码。
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.
这篇关于有多糟糕 - 内联js调用外部处理程序定义VS完全外部js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!