¿Cómo puedo asignar un elemento a la variable?

For example: I want to create shortcut to element array

var $artifacts = $('.game-artifact');

but atm there aren't any elements with such class. Then comes some code, which adds elements. The question is if, after I add these elements will variable $artifacts still refer to them or it will remain null? If so, how I manage to assign a reference to function to a variable?

preguntado el 28 de mayo de 14 a las 13:05

FWIW, $artifacts no será null in the first place. Empty jQuery objects are still objects, not null. -

what you are looking for is object binding. Like said here often enough, $artifacts will remain empty until you reasign it with new values. Here is demo of that behaviour: jsfiddle.net/F7juA -

3 Respuestas

It will remain empty. You can update the reference once you have already added the elements:

// add elements
artifacts = $('.game-artifact');

Eche un vistazo a violín.

contestado el 28 de mayo de 14 a las 13:05

So do I have to manually update each reference or is there any magic way to do so? Like reference in c++ ( a &= b ) - Selenir

I don't see how you could do it "beforehand". Since you can add elements dynamically at any point (f.e. by asynchronous ajax calls) you'll never know what to point at, at the time of variable declaration. - Mareckmareck

You can wrap it with function which will return current elements:

var artifacts = function(){
  return $('.game-artifact');
};

var $artifacts = artifacts();

contestado el 28 de mayo de 14 a las 13:05

Do you really define a function for each query? - Carnero

@undefined No, I do not. - hsz

IMHO this is an anti-pattern. If artifacts was a public method of an object then it would make more sense. - Carnero

You should use .get() over accessing the array directly, to avoid out of bound errors.

var lists = $("body li");
console.log(lists.length);  // returns 20
console.log(lists.get(25)); // returns undefined.
console.log(lists[25]);     // Generates an error.

Respondido 12 Feb 18, 09:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.