Foros del Web » Programando para Internet » Jquery »

jQuery: Problemas con uso de variable

Estas en el tema de jQuery: Problemas con uso de variable en el foro de Jquery en Foros del Web. Hola a tod@s, hoy he empezado con jQuery, y ya me ha surgido esta duda: ¿cómo puedo utilizar una variable JavaScript (ej: var myvar = ...
  #1 (permalink)  
Antiguo 25/07/2009, 06:11
Avatar de Legoltaz  
Fecha de Ingreso: agosto-2008
Mensajes: 325
Antigüedad: 15 años, 8 meses
Puntos: 6
jQuery: Problemas con uso de variable

Hola a tod@s, hoy he empezado con jQuery, y ya me ha surgido esta duda: ¿cómo puedo utilizar una variable JavaScript (ej: var myvar = 50;) en jQuery?

Código JavaScript:
Ver original
  1. var trueWidth = this.width;
  2. var trueHeight = this.height;
  3. $(this).animate({width:trueWidth,height:trueHeight},"slow");

Necesito asignarle al width y height del animate las variables trueWidth y trueHeight respectivamente, pero no me funciona del modo que ahí muestro. ¿Algún consejo? (repito que hoy mismo he empezado con jQuery y estoy totalmente verde ).

Otra pregunta: ¿Cómo puedo acceder a las propiedades de un objeto en jQuery? (ej: $("#elemento").width)?

Última edición por Legoltaz; 25/07/2009 a las 07:16
  #2 (permalink)  
Antiguo 25/07/2009, 08:07
Avatar de Legoltaz  
Fecha de Ingreso: agosto-2008
Mensajes: 325
Antigüedad: 15 años, 8 meses
Puntos: 6
Respuesta: Usar variable de JavaScript en jQuery

Ahora la duda es otra :

Tengo este código:

Código JavaScript:
Ver original
  1. $(document).ready(function(){
  2.     imgs = document.getElementsByTagName("img");
  3.     $.each(imgs,function(i,n){
  4.         w = n.width;
  5.     });
  6.     $("img").css({width:80,height:80});
  7.     $("img").click(function(){
  8.         alert(w);
  9.     });
  10. });

¿Por qué en el alert(w) no me dice el valor del width inicial de la imagen clickeada (me devuelve el valor del width de la segunda imagen)? Ese es mi actual y gran problema y espero que podáis ayudarme :(.

Es decir:

Tengo 2 imagenes:

Width original 1ª img: 460
Width original 2ª img: 135
Width final 1ª img: 80
Width final 2ª img: 80

Solo me devuelve 135.

Quiero obtener el valor del width/height original de cada imagen, luego reducir los width/height a 80, y finalmente usar el width/height original que está almacenado en una variable, cuyo valor no me devuelve correctamente (solo me devuelve 135). Estoy desesperado xd

Última edición por Legoltaz; 25/07/2009 a las 08:16
  #3 (permalink)  
Antiguo 25/07/2009, 09:20
Avatar de eall  
Fecha de Ingreso: noviembre-2008
Ubicación: Concepcion
Mensajes: 127
Antigüedad: 15 años, 5 meses
Puntos: 8
Respuesta: jQuery: Problemas con uso de variable

el problema es que lo que tu quieres hacer está fuera del each.

Código javascript:
Ver original
  1. $(document).ready(function(){
  2.     imgs = document.getElementsByTagName("img");
  3.     $.each(imgs,function(i,n){
  4.         w = n.width; // w queda con el último valor.
  5.     });
  6.     $("img").css({width:80,height:80});
  7.     $("img").click(function(){
  8.         alert(w);
  9.     });
  10. });
  11.  
  12. $('img').click(function(){
  13.    var h = $(this).attr('width');
  14.    var w = $(this).attr('height');
  15.    $(this).animate({width:w,height:h},"slow");
  16. });

espero te ayude con tu problema...
__________________
tutoriales xajax, jQuery, PHP y otros en mi blog
  #4 (permalink)  
Antiguo 25/07/2009, 09:24
Avatar de Legoltaz  
Fecha de Ingreso: agosto-2008
Mensajes: 325
Antigüedad: 15 años, 8 meses
Puntos: 6
Respuesta: jQuery: Problemas con uso de variable

Cita:
Iniciado por eall Ver Mensaje
el problema es que lo que tu quieres hacer está fuera del each.

Código javascript:
Ver original
  1. $(document).ready(function(){
  2.     imgs = document.getElementsByTagName("img");
  3.     $.each(imgs,function(i,n){
  4.         w = n.width; // w queda con el último valor.
  5.     });
  6.     $("img").css({width:80,height:80});
  7.     $("img").click(function(){
  8.         alert(w);
  9.     });
  10. });
  11.  
  12. $('img').click(function(){
  13.    var h = $(this).attr('width');
  14.    var w = $(this).attr('height');
  15.    $(this).animate({width:w,height:h},"slow");
  16. });

espero te ayude con tu problema...
Gracias por la respuesta, pero aún no está bien. Ahora al hacer click no hace nada, porque creo que se le está asignando de nuevo 80px de width height con h y w.

Estaba probando con esto, pero solo me funciona con la última imagen (le asigna a todas las imagenes los valores width y height de la ultima):

Código JavaScript:
Ver original
  1. $(document).ready(function(){
  2.     $("img").each(function(){
  3.         w = $(this).width();
  4.         h = $(this).height();
  5.     });
  6.     $("img").css({width:80,height:80});
  7.     $("img").click(function(){
  8.         $(this).animate({width:w,height:h},"slow");
  9.     });
  10. });
  #5 (permalink)  
Antiguo 25/07/2009, 21:46
Avatar de eall  
Fecha de Ingreso: noviembre-2008
Ubicación: Concepcion
Mensajes: 127
Antigüedad: 15 años, 5 meses
Puntos: 8
Respuesta: jQuery: Problemas con uso de variable

Ya entendí lo que quieres hacer.

Guarda en un atributo las dimensiones originales y cuando le hagas clic las rescatas y las cambias.

Código javascript:
Ver original
  1. $(document).ready(function(){
  2.     $("img").each(function(){
  3.         w = $(this).width();
  4.         h = $(this).height();
  5.         $(this).attr("dim", w + ":" + h);
  6.         $(this).css({width:80,height:80});
  7.     });
  8.     //$("img").css({width:80,height:80});
  9.     $("img").click(function(){
  10.         var d = $(this).attr("dim").split(":");
  11.         $(this).animate({width:d[0],height:d[1]},"slow");
  12.     });
  13. });

pruebalo y me dices como te fue.
__________________
tutoriales xajax, jQuery, PHP y otros en mi blog
  #6 (permalink)  
Antiguo 26/07/2009, 00:20
Avatar de Legoltaz  
Fecha de Ingreso: agosto-2008
Mensajes: 325
Antigüedad: 15 años, 8 meses
Puntos: 6
Respuesta: jQuery: Problemas con uso de variable

Cita:
Iniciado por eall Ver Mensaje
Ya entendí lo que quieres hacer.

Guarda en un atributo las dimensiones originales y cuando le hagas clic las rescatas y las cambias.

Código javascript:
Ver original
  1. $(document).ready(function(){
  2.     $("img").each(function(){
  3.         w = $(this).width();
  4.         h = $(this).height();
  5.         $(this).attr("dim", w + ":" + h);
  6.         $(this).css({width:80,height:80});
  7.     });
  8.     //$("img").css({width:80,height:80});
  9.     $("img").click(function(){
  10.         var d = $(this).attr("dim").split(":");
  11.         $(this).animate({width:d[0],height:d[1]},"slow");
  12.     });
  13. });

pruebalo y me dices como te fue.
No sé por qué, pero sigue sin funcionar, ahora ni siquiera reduce el width y heigth de las imágenes a 80.
  #7 (permalink)  
Antiguo 26/07/2009, 02:04
Avatar de Legoltaz  
Fecha de Ingreso: agosto-2008
Mensajes: 325
Antigüedad: 15 años, 8 meses
Puntos: 6
Respuesta: jQuery: Problemas con uso de variable

¡Solucionado!

Al final el código queda así:

Código JavaScript:
Ver original
  1. $(document).ready(function(){
  2.     $("img").each(function(n){
  3.         w = $(this).width();
  4.         h = $(this).height();
  5.         $(this).attr("dims",w+","+h);
  6.     });
  7.     $("img").css({width:80,height:80});
  8.     $("img").click(function(){
  9.         d = $(this).attr("dims").split(",");
  10.         $(this).animate({width:d[0],height:d[1]},"slow");
  11.     });
  12. });

Muchas gracias por tu ayuda, eall.
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 11:17.