jQuery currently provides me with an interesting introduction to Javascript after 12 years of survival happily without. I am at the stage where I try to learn as much as possible about how to optimize the code that I write, and although I found a lot of good reference material, there is something pretty basic that puzzles me, and I could not find what - Anything about it anywhere.
When I attach something to an element, how should I refer to this element inside the function. For example, when attaching a function to the click event of an element:
$('#a_button',$('#a_list_of_buttons')).click(function() {
I know that you should not re-select it so that the browser again searches the entire DOM from scratch to find what it already found once:
$('#a_button').click(function() { // I KNOW THAT THIS IS NAUGHTY var buttonValue = $('#a_button').val(); $('#a_button').addClass('button_has_been_clicked'); });
I am currently using one of the following, but I'm not quite sure what they are actually doing:
$('#a_button').click(function() {
But is it just a second choice, as in the first "naughty" example?
$('#a_button').click(function(event) {
It seems like it could be better, but is it possible to reference event.target several times?
$('#a_button').click(function(event) {
I understand the efficiency of data transfer performance in variables, but I'm not sure whether or not in these situations using $ (this) or $ (event.target) gives me the same efficiency already by setting a new variable. I actually Iām doing more work that I need.
Thanks.
optimization javascript jquery
Chris stevenson
source share