我试图理解为什么 this jsperf test 中的一个片段似乎比其他片段慢得多。
这是四个片段:
$(".menu-vertical li.selected > ul.static").show().parents().show();
$('ul.root').find('li.selected').children('ul.static').show().parents().show();
$("ul.root li.selected > ul.static").show().parents().show();
$('ul.root li.selected').children('ul.static').show().parents().show();
第二个似乎在所有浏览器中都变慢了,我不明白为什么。
最佳答案
是什么让第二个与其他的不同?
$('ul.root') // you get the collection of all `ul.root`
.find('li.selected') // in each collection you search for `li.selected`
.children('ul.static') // you get `ul.static` children elements of each found
...
请注意您需要进行多少次迭代。在所有其他示例中,大多数搜索是在单个查询中执行的,其评估速度要快许多倍。
关于jquery - Find/Children 与后代选择器 jquery 性能差异,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13725053/