jQuery链式调用性能

12

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

$(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);

即使第二种方法更快,将它们分开写会使代码更易读,这样做是否更好?

2个回答

28
不,两者在速度上不等同。
每次$(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
});

3
那是一个完整的解释! - A. Wolff

5
为了易读性,您可以将该行分成若干段。
$(this)
    .attr("date",date)
    .attr("date_start",date_start)
    .attr("heure_start",heure_start);

我知道这本该是一条评论,但如果写成评论,格式会很乱。

这句话与IT技术无关。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接