【问题标题】:Is vertically lining up code in jQuery considered harmful?在 jQuery 中垂直排列代码是否有害?
【发布时间】:2015-03-17 22:20:40
【问题描述】:

这段代码:

if (this.config.imageTarget) {
    this.caption = $('<div />')
           .addClass('finaff-lightbox-caption')
                   .html(content.html())
                   .appendTo(this.wrapper)
                   .hide(); // starts out hidden

    this.captionSpacer = $('<div>&nbsp;</div>')
                         .appendTo(this.contentContainer)
                         .hide();

...导致 JSLint 达到顶峰。它说:

  if (this.config.imageTarget) {
  58                      this.caption = $('<div />')
  59                                     .addClass('finaff-lightbox-caption')
      ==========================^
      lint warning: unexpected end of line; it is ambiguous whether these lines are part of the same statement
  60                                     .html(content.html())
      ===================================^
      lint warning: unexpected end of line; it is ambiguous whether these lines are part of the same statement
  61                                     .appendTo(this.wrapper)
      ===================================^
      lint warning: unexpected end of line; it is ambiguous whether these lines are part of the same statement
  62                                     .hide();

真的有必要像这样将这类代码折叠在一起吗:

. . .
this.caption = $('<div />').addClass('finaff-lightbox-caption').html(content.html()).appendTo(this.wrapper).hide();
. . .

?

通过排列点将其分开对我来说很有意义;使其更容易阅读/摸索。我希望这只是 JSLint 扮演的白手套婆婆。

【问题讨论】:

  • JSLint 通常过于严格——而且通常不应被誉为调试 JS 的唯一黄金标准。尝试使用JSHint 代替(ta-da,您的代码检查得非常好,没有$ 未定义变量,但这很正常,因为它不知道您将它用作 jQuery别名)。我更喜欢在方法链超过适合视口宽度的线时使用换行符,以获得更好的可读性 - 并且在超越 DOM 时指示您处于哪个“级别”也非常有用:)
  • ... 这就是 JSHint 的来源。

标签: jquery jslint


【解决方案1】:

您只需将white 选项(用于空格)设置为true。

这段代码在JSLint.com:

/*jslint white:true */
/*global $, content */
if (this.config.imageTarget) {
    this.caption = $('<div />')
           .addClass('finaff-lightbox-caption')
                   .html(content.html())
                   .appendTo(this.wrapper)
                   .hide(); // starts out hidden

    this.captionSpacer = $('<div>&nbsp;</div>')
                         .appendTo(this.contentContainer)
                         .hide();
}

我所做的唯一更改是:

  • 将 jslint 指令 white 设置为 true(容忍非严格的空白规则)
  • 为 jQuery 和 content 添加了 global
    • 不确定content 是什么;
    • 注意:使用global 几乎肯定不是处理content 的最佳方式
  • 为您的 if 添加了结束 } 括号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    相关资源
    最近更新 更多