【问题标题】:jQuery chaining performancejQuery 链接性能
【发布时间】:2012-12-01 11:01:15
【问题描述】:

这些在速度方面是否相等?

$(this).attr("date",date);
$(this).attr("date_start",date_start);
$(this).attr("heure_start",heure_start);

$(this).attr("date",date).attr("date_start",date_start).attr("heure_start",heure_start);

即使第二个更快,是否最好单独编写以使代码更具可读性?

【问题讨论】:

    标签: jquery performance chaining


    【解决方案1】:

    不,两者在速度上不相等。

    $(this) 每次都会构建一个新的 jQuery 对象。并且取决于this 是什么,这可能是一个复杂的操作。

    所以第二种形式更快。

    请注意,为了便于阅读,您可以将其写为

    $(this)
        .attr("date",date)
        .attr("date_start",date_start)
        .attr("heure_start",heure_start);
    

    如果由于中间有其他代码行而无法链接操作,您也可以缓存对象。这很正常:

    var $this = $(this);
    $this.attr("date", date);
    $this.attr("date_start", date_start);
    $this.attr("heure_start", heure_start);
    

    还要注意attr 可以将地图作为参数:

    $(this).attr({
        date: date,
        date_start: date_start,
        heure_start: heure_start
    });
    

    【讨论】:

    • 这就是一个完整的解释!
    【解决方案2】:

    为了便于阅读,您可以将行拆分为

    $(this)
        .attr("date",date)
        .attr("date_start",date_start)
        .attr("heure_start",heure_start);
    

    我知道这应该是一个注释,但间距作为一个没有意义。

    【讨论】:

      猜你喜欢
      • 2011-05-10
      • 2012-01-07
      • 2016-02-11
      • 2011-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-30
      相关资源
      最近更新 更多