Foros del Web » Programando para Internet » Javascript »

Función se vuelve undefined de repente

Estas en el tema de Función se vuelve undefined de repente en el foro de Javascript en Foros del Web. Tengo esta función para controlar la opacidad de un elemento. Lo que hago es que si tiene argumentos, la seteo, y si no devuelvo su ...
  #1 (permalink)  
Antiguo 13/01/2011, 13:45
Avatar de _cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 10 meses
Puntos: 310
Función se vuelve undefined de repente

Tengo esta función para controlar la opacidad de un elemento. Lo que hago es que si tiene argumentos, la seteo, y si no devuelvo su opacidad actual. Lo tengo así:
Código Javascript:
Ver original
  1. HTMLElement.prototype.opacity=function(){
  2.  var isIE = document.all, estilos = isIE ? ['filters', 'alpha', 100] : ['style', 'opacity', 1];
  3.  if(arguments.length)
  4.   this[estilos[0]][estilos[1]] = arguments[0] * estilos[2];
  5.  else{
  6.   if(this[estilos[0]][estilos[1]]){
  7.    return this[estilos[0]][estilos[1]]/estilos[2];
  8.   }else{
  9.    alert(SS==undefined); // false
  10.    if(SS.find(this.tagName, isIE?'filter':'opacity')){
  11.     return isIE?(SS.find(this.tagName, 'filter')).match(/\d+/)[0]/100:SS.find(this.tagName, 'opacity');
  12.    }else{
  13.     alert(SS==undefined); // true
  14.     if(SS.find('#'+this.id, isIE?'filter':'opacity'))
  15.      return isIE?(SS.find('#'+this.id, 'filter')).match(/\d+/)[0]/100:SS.find('#'+this.id, 'opacity');
  16.     else{
  17.      for(var i=0, partir=this.className.split(' '); clase=partir[i]; i++){
  18.       if(SS.find('.'+clase, isIE?'filter':'opacity'))
  19.        return isIE?(SS.find('.'+clase, 'filter')).match(/\d+/)[0]/100:SS.find('.'+clase, 'opacity');
  20.      }
  21.     }
  22.    }
  23.   }
  24.  }
  25.  return 1;
  26. };
SS es un objeto para trabajar con StyleSheets, pero a mitad de la función deja de reconocerlo
¿Alguien ve el problema? Yo llevo desde ayer y nada.
Saludos (:
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red
  #2 (permalink)  
Antiguo 13/01/2011, 15:57
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Función se vuelve undefined de repente

Sin el objeto SS no se puede debugear, podes postearlo con algún ejemplo de uso o es TOP-SECRET :)
  #3 (permalink)  
Antiguo 13/01/2011, 17:06
Avatar de _cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 10 meses
Puntos: 310
Respuesta: Función se vuelve undefined de repente

Jajaja, este es el código:
Código Javascript:
Ver original
  1. String.prototype.low=function(){ return this.toLowerCase(); };
  2. var extSS = function(){};
  3. extSS.prototype = {
  4.  isIE : document.all,
  5.  instrucciones : {
  6.   'reglas' : this.isIE ? 'rules' : 'cssRules',
  7.   'add' : (this.isIE ? 'add' : 'insert') + 'Rule',
  8.   'remove' : (this.isIE ? 'remove' : 'delete') + 'Rule'
  9.  },
  10.  hojas : document.styleSheets,
  11.  getSS : function(id){
  12.   var cosa;
  13.   switch(typeof id){
  14.    case 'number' :
  15.     return this.hojas[id] ? this.hojas[id] : false;
  16.    break;
  17.    case 'string' :
  18.     for(var url = /(file|http):\/\/(\/*).+\//, i=0; cosa = this.hojas[i]; i++){
  19.      if(cosa.href == id || cosa.href.replace(url) == id || cosa.href.replace(url, '').replace(/\.css$/, '') == id)
  20.       return cosa;
  21.     }
  22.    break;
  23.   }
  24.   return false;
  25.  },
  26.  find : function(select, propi){
  27.   var estilo;
  28.   for(i=0; SS = this.hojas[i]; i++){  
  29.    estilo = SS[this.instrucciones['reglas']];
  30.    for(j=0; regla = estilo[j]; j++){
  31.     if(regla.selectorText.low() == select.low() && regla.style[propi])
  32.      return regla.style[propi];
  33.    }
  34.   }
  35.   return false;
  36.  },
  37.  set : function(select, propi, val){
  38.   var estilo;
  39.   for(i=0; SS = this.hojas[i]; i++){  
  40.    estilo = SS[this.instrucciones['reglas']];
  41.    for(j=0; regla = estilo[j]; j++){
  42.     if(regla.selectorText.low() == select.low() && regla.style[propi])
  43.      regla.style[propi] = val;
  44.    }
  45.   }
  46.   return false;
  47.  },
  48.  add : function(hoja, select, propi, val){
  49.   var SS = this.getSS(hoja);
  50.   try{
  51.    SS.insertRule(select + '{' + propi + ':' + val + '}', SS[this.instrucciones['reglas']].length);
  52.   }catch(e){ // IE
  53.    SS.addRule(select, propi + ':' + val);
  54.   }
  55.  },
  56.  remove : function(hoja, select){
  57.   var estilo;
  58.   switch(typeof hoja){
  59.    case 'number' :
  60.     estilo = this.hojas[hoja][this.instrucciones['reglas']];
  61.     for(i=0; regla = estilo[i]; i++){
  62.      if(regla.selectorText.low() == select.low())
  63.       this.getSS(hoja)[this.instrucciones['remove']](j);
  64.     }
  65.    break;  
  66.    case 'string' :
  67.     if(hoja=='all'){
  68.      for(i=0; SS = this.hojas[i]; i++){
  69.       estilo = SS[this.instrucciones['reglas']];
  70.       for(j=0; regla = estilo[j]; j++){
  71.        if(regla.selectorText.low() == select.low())
  72.         SS[this.instrucciones['remove']](j);
  73.       }
  74.      }
  75.     }else{
  76.      var SS = this.getSS(hoja), estilo = SS[this.instrucciones['reglas']];
  77.      for(i = 0; regla = estilo[i]; i++){
  78.       if(regla.selectorText.low() == select.low())
  79.        SS[this.instrucciones['remove']](i)
  80.      }
  81.     }
  82.    break;
  83.   }
  84.  }
  85. };
  86. var SS = new extSS();
Los códigos son los de @JavierB, pero yo los junté en un sólo objeto.
Saludos (:
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red

Última edición por _cronos2; 13/01/2011 a las 17:11
  #4 (permalink)  
Antiguo 13/01/2011, 18:31
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Función se vuelve undefined de repente

Aca vuelo _cronos2, el problema esta en SS , el objecto se reasigna dentro de la "clase", en varios lugares hace lo mismo, toma por ejemplo el find que en tu caso es el que te hace saltar el error,

Código Javascript:
Ver original
  1. find : function(select, propi){
  2.    var estilo;
  3.    for(i=0; SS = this.hojas[i]; i++){  
  4.    ...
  5.    }
  6.    ...
  7. }

Al no declarar var SS para que tenga scope local, se reasigna SS, en varias funciones esta asi en otras esta como variable local, deberías revisar el script.

Saludos.
  #5 (permalink)  
Antiguo 14/01/2011, 00:38
Avatar de _cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 10 meses
Puntos: 310
Respuesta: Función se vuelve undefined de repente

Muchas gracias, me imaginaba que el problema era algo así, porque antes lo tenía con otro nombre y funcionaba, pero no me daba cuenta de dónde fallaba xD Pero dentro del for, en la segunda parte, ¿se puede poner var? ¿O tendré que cambiar todos los SS que haya?
Edit: En FF, si pongo
Cita:
for(i=0; var SS = this.hojas[i]; i++){
me salta un syntax error, así que tendré que cambiarlos todos
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red
  #6 (permalink)  
Antiguo 14/01/2011, 14:06
Avatar de _cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 10 meses
Puntos: 310
Respuesta: Función se vuelve undefined de repente

Muchas gracias a todos, ya está solucionado. Al final el código quedó así:
Código Javascript:
Ver original
  1. String.prototype.low=function(){ return this.toLowerCase(); };
  2. var extSS = function(){};
  3. extSS.prototype = {
  4.  isIE : document.all,
  5.  instrucciones : {
  6.   'reglas' : this.isIE ? 'rules' : 'cssRules',
  7.   'add' : (this.isIE ? 'add' : 'insert') + 'Rule',
  8.   'remove' : (this.isIE ? 'remove' : 'delete') + 'Rule'
  9.  },
  10.  hojas : document.styleSheets,
  11.  getSS : function(id){
  12.   var cosa;
  13.   switch(typeof id){
  14.    case 'number' :
  15.     return this.hojas[id] ? this.hojas[id] : false;
  16.    break;
  17.    case 'string' :
  18.     for(var url = /(file|http):\/\/(\/*).+\//, i=0; cosa = this.hojas[i]; i++){
  19.      if(cosa.href == id || cosa.href.replace(url, '') == id || cosa.href.replace(url, '').replace(/\.css$/, '') == id)
  20.       return cosa;
  21.     }
  22.    break;
  23.   }
  24.   return false;
  25.  },
  26.  find : function(select, propi){
  27.   var estilo;
  28.   for(i=0; sheet = this.hojas[i]; i++){  
  29.    estilo = sheet[this.instrucciones['reglas']];
  30.    for(j=0; regla = estilo[j]; j++){
  31.     if(regla.selectorText.low() == select.low() && regla.style[propi])
  32.      return regla.style[propi];
  33.    }
  34.   }
  35.   return false;
  36.  },
  37.  set : function(select, propi, val){
  38.   var estilo;
  39.   for(i=0; sheet = this.hojas[i]; i++){  
  40.    estilo = sheet[this.instrucciones['reglas']];
  41.    for(j=0; regla = estilo[j]; j++){
  42.     if(regla.selectorText.low() == select.low() && regla.style[propi])
  43.      regla.style[propi] = val;
  44.    }
  45.   }
  46.   return false;
  47.  },
  48.  add : function(hoja, select, propi, val){
  49.   var SS = this.getSS(hoja);
  50.   try{
  51.    SS.insertRule(select + '{' + propi + ':' + val + '}', SS[this.instrucciones['reglas']].length);
  52.   }catch(e){ // IE
  53.    SS.addRule(select, propi + ':' + val);
  54.   }
  55.  },
  56.  remove : function(hoja, select){
  57.   var estilo;
  58.   switch(typeof hoja){
  59.    case 'number' :
  60.     estilo = this.hojas[hoja][this.instrucciones['reglas']];
  61.     for(i=0; regla = estilo[i]; i++){
  62.      if(regla.selectorText.low() == select.low())
  63.       this.getSS(hoja)[this.instrucciones['remove']](j);
  64.     }
  65.    break;  
  66.    case 'string' :
  67.     if(hoja=='all'){
  68.      for(i=0; sheet = this.hojas[i]; i++){
  69.       estilo = sheet[this.instrucciones['reglas']];
  70.       for(j=0; regla = estilo[j]; j++){
  71.        if(regla.selectorText.low() == select.low())
  72.         sheet[this.instrucciones['remove']](j);
  73.       }
  74.      }
  75.     }else{
  76.      var SS = this.getSS(hoja), estilo = SS[this.instrucciones['reglas']];
  77.      for(i = 0; regla = estilo[i]; i++){
  78.       if(regla.selectorText.low() == select.low())
  79.        SS[this.instrucciones['remove']](i)
  80.      }
  81.     }
  82.    break;
  83.   }
  84.  }
  85. };
  86. var SS = new extSS();
Saludos (:
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red
  #7 (permalink)  
Antiguo 14/01/2011, 14:14
Avatar de _cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 10 meses
Puntos: 310
Respuesta: Función se vuelve undefined de repente

Ya que estamos, ¿me podéis ayudar con la función opacity()? Quiero decir, funciona bien, pero cuando tiene que buscar la opacidad de un elemento, es bastante ineficiente. Si yo tengo div#a{opacity:0.5} devolverá 1, porque sólo busca por tagName, id y class solas. Es decir, si pone #a, si lo reconocerá, pero div#a no. ¿Hay alguna manera de solucionarlo? Hice estas funciones para elaborar la ruta de un elemento:
Código Javascript:
Ver original
  1. HTMLElement.prototype.identify=function(){
  2.  var str=' '+this.tagName.toLowerCase();
  3.  return str+=(this.id?'#'+this.id+' ':'')+(this.className?'.'+this.className:'')+' ';
  4. }
  5. HTMLElement.prototype.makeRoute=function(){
  6.  var obj=this, str=this.identify();
  7.  while(obj.parentNode.parentNode){
  8.   obj=obj.parentNode;
  9.   str=obj.identify()+'>'+str;
  10.  }
  11.  return str;
  12. };
Pero no sé cómo usarlas para mi propósito. Gracias otra vez.
Saludos (:
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red
  #8 (permalink)  
Antiguo 14/01/2011, 15:22
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 19 años, 10 meses
Puntos: 834
Respuesta: Función se vuelve undefined de repente

No sé el grado de compatibilidad estás buscando. Quizá podrías jugar con querySelectorAll. Tampoco me imagino cómo harás funcionar tu código en Explorer, que normalmente no permite modificar el prototipo de un elemento html. La verdad es que para extender un objeto html prefiero usar mixin.
  #9 (permalink)  
Antiguo 14/01/2011, 16:21
Avatar de _cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 10 meses
Puntos: 310
Respuesta: Función se vuelve undefined de repente

Sé que esto no va a ser nada original, pero odio IE ¬¬ ¿Podrías explicarme un poco eso de querySelectorAll y mixin?
Saludos (:
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red
  #10 (permalink)  
Antiguo 15/01/2011, 06:29
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 19 años, 10 meses
Puntos: 834
Respuesta: Función se vuelve undefined de repente

querySelectorAll es un método de referenciación basado en la api selectors de w3c. Tiene bastante buen soporte para los navegadores modernos. Este es un enlace interesante: http://www.javascriptkit.com/dhtmltu...tors_api.shtml

Mixin consiste en un objeto plantilla que se crea sólo a efectos de que otros objetos hereden de él métodos y propiedades. Un objeto puede heredar de varios mixin. Y varios objetos pueden heredar del mismo mixin.
Un ejemplo puede verse en este post:
http://www.forosdelweb.com/3369479-post8.html
  #11 (permalink)  
Antiguo 15/01/2011, 07:35
Avatar de _cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 10 meses
Puntos: 310
Respuesta: Función se vuelve undefined de repente

Muchísimas gracias, como siempre ¡el código tremendo!
Saludos (:
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red

Etiquetas: undefined, vuelve
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 21:39.