问题
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.
回答1:
DOM selection is expensive. Cache it.
var x = $('#MyElement');
Here's a jsPerf test. In Chrome 13 on Mac OS X, the variable reference is over 1,000 times faster.
This is not only due to the DOM selection of course, but also the construction of the jQuery object.
回答2:
Yes will be better, for performance and coding style.
http://jquery-howto.blogspot.com/2008/12/caching-in-jquery.html
jQuery / javascript caching elements for efficiency?
回答3:
Considering that the second code only queries the DOM once for x
, yes, it is a much better idea to store the jQuery object.
回答4:
why not?
var x = $('#MyElement').text();
$('#MyParentElement').html('<tr id="' + x + '"><td>' + x + '</td></tr>';
回答5:
Someone correct me if I'm wrong, but it's my understanding that if you used the second option (ie var x = $('#myElement')) that it wouldn't update dynamically. If #myElement changed, as elements sometimes do, you'd still be referencing whatever it was when you assigned its value to X.
If you don't feel like #myElement is going to change, then go ahead and use the var x option. As others have said, it's a bit quicker.
回答6:
Storing $('#MyParentElement') in a variable would be faster, however by a small margin since selection by element ID is fast. Though if building a large JS app then it could add up.
回答7:
It's about as okay as calling document.getElementById
every time would be.
Technically it is better to go with your second option, and store the result to a variable if you will be accessing it repeatedly. But in practical terms, unless you have hundreds of references to the same element then the difference is not going to be noticeable to the user.
来源:https://stackoverflow.com/questions/6542646/jquery-is-it-okay-to-use-elementid-everytime