Is jQuery traversal preferred over selectors?

后端 未结 2 1863
长发绾君心
长发绾君心 2020-12-12 20:41

Is using $(\"#vacations\").find(\"li\").last() is a better practice than $(\"#vacations li:last\")?

Background and my thoughts:

I w

2条回答
  •  春和景丽
    2020-12-12 21:16

    Here's a test for your setup: http://jsperf.com/andrey-s-jquery-traversal

    Sizzle, jQuery's selector engine, parses the string with regex and tries to speed up very basic selectors by using getElementById and getElementsByTagName. If your selector is anything more complicated than #foo and img, it'll try to use querySelectorAll, which accepts only valid CSS selectors (no :radio, :eq, :checkbox or other jQuery-specific pseudo-selectors).

    The selector string is both less readable and slower, so there's really no reason to use it.

    By breaking the selector string up into simple chunks that Sizzle can parse quickly (#id and tagname), you're basically just chaining together calls to getElementById and getElementsByTagName, which is about as fast as you can get.

提交回复
热议问题