理论上,以下哪一项在性能和/或内存方面会更好?换句话说,jQuery 是否必须多次选择同一个项目,或者它是否知道它过去选择了哪些项目?
我故意让 animate 不带任何参数,这是一个纯粹的理论问题。
$("#someelement").animate();
$("#someelement").animate();
$("#someelement").animate();
$("#someelement").animate();
$("#someelement").animate();
$("#someelement").animate();
$("#someelement").animate();
$("#someelement").animate();
$("#someelement").animate();
$("#someelement").animate();
或
var element = $("#someelement");
element.animate();
element.animate();
element.animate();
element.animate();
element.animate();
element.animate();
element.animate();
element.animate();
element.animate();
element.animate();
最佳答案
肯定是选项 2。对于选项 1,jQuery 必须在每次动画之前找到 DOM 中的元素。
使用选项 2,元素会“缓存”在变量中,无需再次遍历 DOM。
关于javascript - 使用 jQuery 多次选择同一个项目 vs 使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3535033/