简体   繁体   English

jQuery链接性能

[英]jQuery chaining performance

Are these equivalent in term of speed ? 这些在速度方面是否相同?

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

or 要么

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

Even if the second is faster is it better to write it separate to make the code more readable? 即使第二个更快,最好将它单独编写以使代码更具可读性?

No, the two aren't equivalent in speed. 不,这两者在速度上并不相同。

$(this) builds a new jQuery object each time. $(this)每次都构建一个新的jQuery对象。 And depending on what is this , this can be a complex operation. 并根据什么是this ,这是一个复杂的操作。

So the second form is faster. 所以第二种形式更快。

Note that for readibility you can write it as 请注意,为了便于阅读,您可以将其编写为

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

If you can't chain the operations because you have other lines of code in between, you can also cache the object. 如果由于中间有其他代码行而无法链接操作,则还可以缓存该对象。 This is usual : 这通常是:

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

And note also that attr can take a map as argument : 还要注意attr可以将地图作为参数:

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

For readability purposes you could split the line to 出于可读性目的,您可以将行拆分为

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

I know this should have been a comment but the spacing would have made no sense as one. 我知道这应该是一个评论,但是间距本来就没有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM