Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
595 views
in Technique[技术] by (71.8m points)

jquery - Which is more efficient: .parent().parent().parent() ~or~ parents(".foo") ~or~ closest(".foo")

I have an A tag which triggers the animation of it's great-great-great-grandparent. All of the following will work, but which is most efficient, and why?

$(this).parent().parent().parent().parent().parent().animate(...);

$(this).parents(".foo").animate(...);

$(this).closest(".foo").animate(...);

I suspect that the first might be, as it's the most explicit, but for maintenance reasons (the nesting may change) I prefer the second. They all appear to run smoothly in practice.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here’s an analyzation:

  • parent() walks just one level up in the DOM tree.
  • parents(".foo") walks up to the root and selects only those elements that match the given selector .foo.
  • closest(".foo") walks up to the root but stops once an element matches the selector .foo.

So I would choose the last one, closest(".foo"). The reason:

  • It’s better than chaining parent, because if your document changes because you removed or added one hierarchy, you don’t need to change the jQuery code.
  • It’s better than parents(".foo"), because it stops as soon as a match has been found.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...