jQuery-每次都可以使用$('#ElementId')吗? [英] jQuery - Is it okay to use $('#ElementId') everytime?

查看:197
本文介绍了jQuery-每次都可以使用$('#ElementId')吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚学习了如何在jQuery中进行"document.getElementById"对应功能(功能更强大).我的问题是,每次或每行代码都可以使用它吗?这是我现在的使用方式:

I just learned how to do the 'document.getElementById' counterpart in jQuery (and it's more powerful). My question is, is it okay to use it everytime or every line of code? Here's how I use it now:

$('#MyParentElement').html('<tr id="' + $('#MyElement').val() + '"><td>' + $('#MyElement').val() + '</td></tr>';

如果我做类似使用变量来引用对象的事情,那会更好吗?

Isn't better if I do something like using a variable to reference the object?

var x = $('#MyElement');
$('#MyParentElement').html('<tr id="' + x.text() + '"><td>' + x.text() + '</td></tr>';

请注意,我更关注性能,而不是代码的整洁度.

Note that I'm more concern of the performance, not the cleanliness of the codes.

推荐答案

DOM选择非常昂贵.缓存它.

DOM selection is expensive. Cache it.

var x = $('#MyElement');


这是一个jsPerf测试.在Mac OS X上的Chrome 13中,变量引用的运行速度快了1000倍.


Here's a jsPerf test. In Chrome 13 on Mac OS X, the variable reference is over 1,000 times faster.

这不仅是由于DOM选择,而且还取决于jQuery对象的构造.

This is not only due to the DOM selection of course, but also the construction of the jQuery object.

这篇关于jQuery-每次都可以使用$('#ElementId')吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆