这是多么糟糕 - 使用外部处理程序定义的内联 js 调用 VS 完全外部 js
我在我的项目中遇到以下代码:
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");
首先我认为这段代码是错误的,我必须将其重写为外部代码,即
jQuery('#addmore)'.click(function add_table(elem){
var current_id = jQuery("table.t1:last").attr("id");
但是后来我再次查看它,发现这个 html 更具可读性 - 我看到了哪个函数绑定到html中已有的元素,我不需要在js中搜索它。
当然它没有封装在里面,
jQuery(document).ready(
所以在某些情况下它不会工作
所以问题:这段代码有多糟糕?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是可重用性和个人品味的问题。对于非常简单的事情(例如您的示例),内联代码更具可读性,但当然您依赖于
add_table()
作为全局函数 - 如果您有数百个具有不同点击处理程序的元素,您最终可能会数百个函数/变量污染了全局命名空间。那很糟糕! :)在可重用性方面,我发现最好在抽象功能的不同组件中进行编码,并且可以在需要时调用 - 所有这些都在定义的(非全局)命名空间内。
上面的代码提供了一个很好的关注点分离 - 这意味着语义信息(HTML)忽略了行为信息 (Javascript),这再次有助于创建更清晰、更易于管理的代码。
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.
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.
根据站点的大小(和流量水平),可能会出现带宽问题。即
onclick="add_table(this)"
向下载添加 24 字节数据。这可以放入缓存的 JavaScript 页面中,该页面仅下载一次,而不是针对每个请求下载。如果您有很多包含额外代码的页面,并且您有大量流量,则可能会产生明显的带宽差异。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.