¿Cómo puedo asignar un elemento a la variable?
Frecuentes
Visto 29,671 equipos
8
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?
3 Respuestas
10
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
6
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
1
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 jquery variables reference or haz tu propia pregunta.
FWIW,
$artifacts
no seránull
in the first place. Empty jQuery objects are still objects, notnull
. - Frédéric Hamidiwhat 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 - Nico O