Deprecated: Assigning the return value of new by reference is deprecated in /home/controlz/public_html/blog/wp-settings.php on line 472

Deprecated: Assigning the return value of new by reference is deprecated in /home/controlz/public_html/blog/wp-settings.php on line 487

Deprecated: Assigning the return value of new by reference is deprecated in /home/controlz/public_html/blog/wp-settings.php on line 494

Deprecated: Assigning the return value of new by reference is deprecated in /home/controlz/public_html/blog/wp-settings.php on line 530

Strict Standards: Declaration of Walker_Page::start_lvl() should be compatible with Walker::start_lvl(&$output) in /home/controlz/public_html/blog/wp-includes/classes.php on line 594

Strict Standards: Declaration of Walker_Page::end_lvl() should be compatible with Walker::end_lvl(&$output) in /home/controlz/public_html/blog/wp-includes/classes.php on line 594

Strict Standards: Declaration of Walker_Page::start_el() should be compatible with Walker::start_el(&$output) in /home/controlz/public_html/blog/wp-includes/classes.php on line 594

Strict Standards: Declaration of Walker_Page::end_el() should be compatible with Walker::end_el(&$output) in /home/controlz/public_html/blog/wp-includes/classes.php on line 594

Strict Standards: Declaration of Walker_PageDropdown::start_el() should be compatible with Walker::start_el(&$output) in /home/controlz/public_html/blog/wp-includes/classes.php on line 611

Strict Standards: Declaration of Walker_Category::start_lvl() should be compatible with Walker::start_lvl(&$output) in /home/controlz/public_html/blog/wp-includes/classes.php on line 705

Strict Standards: Declaration of Walker_Category::end_lvl() should be compatible with Walker::end_lvl(&$output) in /home/controlz/public_html/blog/wp-includes/classes.php on line 705

Strict Standards: Declaration of Walker_Category::start_el() should be compatible with Walker::start_el(&$output) in /home/controlz/public_html/blog/wp-includes/classes.php on line 705

Strict Standards: Declaration of Walker_Category::end_el() should be compatible with Walker::end_el(&$output) in /home/controlz/public_html/blog/wp-includes/classes.php on line 705

Strict Standards: Declaration of Walker_CategoryDropdown::start_el() should be compatible with Walker::start_el(&$output) in /home/controlz/public_html/blog/wp-includes/classes.php on line 728

Strict Standards: Redefining already defined constructor for class wpdb in /home/controlz/public_html/blog/wp-includes/wp-db.php on line 306

Deprecated: Assigning the return value of new by reference is deprecated in /home/controlz/public_html/blog/wp-includes/cache.php on line 103

Strict Standards: Redefining already defined constructor for class WP_Object_Cache in /home/controlz/public_html/blog/wp-includes/cache.php on line 425

Deprecated: Assigning the return value of new by reference is deprecated in /home/controlz/public_html/blog/wp-includes/query.php on line 21

Deprecated: Assigning the return value of new by reference is deprecated in /home/controlz/public_html/blog/wp-includes/theme.php on line 623

Strict Standards: Redefining already defined constructor for class WP_Dependencies in /home/controlz/public_html/blog/wp-includes/class.wp-dependencies.php on line 15

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /home/controlz/public_html/blog/wp-settings.php:472) in /home/controlz/public_html/blog/wp-content/plugins/si-captcha-for-wordpress/si-captcha.php on line 31

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/controlz/public_html/blog/wp-settings.php:472) in /home/controlz/public_html/blog/wp-content/plugins/si-captcha-for-wordpress/si-captcha.php on line 31

Strict Standards: call_user_func_array() expects parameter 1 to be a valid callback, non-static method GoogleSitemapGeneratorLoader::Enable() should not be called statically in /home/controlz/public_html/blog/wp-includes/plugin.php on line 311
funcion con parametros para AddEventListener() | formatic.cat

funcion con parametros para AddEventListener()


Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/controlz/public_html/blog/wp-content/plugins/ig_syntax_hilite/geshi.php on line 2056

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/controlz/public_html/blog/wp-content/plugins/ig_syntax_hilite/geshi.php on line 2056

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/controlz/public_html/blog/wp-content/plugins/ig_syntax_hilite/geshi.php on line 2056

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/controlz/public_html/blog/wp-content/plugins/ig_syntax_hilite/geshi.php on line 2056

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/controlz/public_html/blog/wp-content/plugins/ig_syntax_hilite/geshi.php on line 2056

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/controlz/public_html/blog/wp-content/plugins/ig_syntax_hilite/geshi.php on line 2056

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/controlz/public_html/blog/wp-content/plugins/ig_syntax_hilite/geshi.php on line 2056

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/controlz/public_html/blog/wp-content/plugins/ig_syntax_hilite/geshi.php on line 2056

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/controlz/public_html/blog/wp-content/plugins/ig_syntax_hilite/geshi.php on line 2056

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/controlz/public_html/blog/wp-content/plugins/ig_syntax_hilite/geshi.php on line 2056

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/controlz/public_html/blog/wp-content/plugins/ig_syntax_hilite/geshi.php on line 2056

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/controlz/public_html/blog/wp-content/plugins/ig_syntax_hilite/geshi.php on line 2056

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/controlz/public_html/blog/wp-content/plugins/ig_syntax_hilite/geshi.php on line 2056

Queremos definir una función con parametros y asignarla a un evento javascript de un elemento.

El primer problema que encontramos es como lo definimos? Que dice el estandard? tenemos varios modos de hacerlo:

  1. Mediante AddEventListener para navegadores estandard  o con  attachEvent  para explorer
  2. Podremos definir todo el tag mediante innerHTML incrustando ahí la función javascript con tantos parametros como queramos.
  3. podemos igualar el elemento + punto + evento (elemento.onclick='Enviar('+variableGlobal+')');

El estandard dice de usar la primera opción. Pero claro no todos los navegadores son estadards. de todos modos tenemos el problema siguiente, asignar una funcion no da ningun tipo de problema, pero como hacemos cuando queremos declarar una funcion con 1 parametros?

enlace.addEventListener("click", function(){ MyFuncion(parametro1,parametro2);} , false);

Esto funciona bien, pero teniendo en cuenta que parametro1 y parametro2 deberán ser variables globales. Así que si estamos recorriendo un bucle y estas variables son locales, estos parametros solo conservarán el ultimo valor y no los valores del bucle...

Como nos podemos pasar una variable local?  Una solucion un tanto graciosa, es guardarnos el valor en alguna propiedad del elemento que va a recibir el evento. Que quiere decir esto? Pues por ejemplo si este evento se va a asocioar a un link (elemento a) podemos utilizar por ejemplo su atributo id, name, etc... alguno que estemos utilizando. Etonces ahi guardamos el valor que queramos. Al declar

enlace.name=mivariableLocal;

enlace.addEventListener("click", function(event){ Envio(event.target.getAttribute('name');} , false);

Ahora estamos guardando el valor de la variable en un atributo del enlace, asi, cuando declaramos la funcion, le pasamos el evento y desde el evento nos es facil recuperar ese elemento y consultar la propiedad donde previamente nos hemos guardado el valor necesairo para pasarle a la función.

Que pasa si me quiero pasar 2 o más parámetros a un función. Bueno, podriamos crear un Array global donde en cada posición del array pusieramos los parametros necesarios para la funcion. y el indice de la matriz lo guardamos en alguna propiedad. Y a la función pasandolo ese parametros accedemos al Array global a consultar los parametros que queriamos pasarle.

Evidentemente existen otras maneras, podeis buscar por los "callBacks" una solucion  donde se crea un handler capaz de pasar parametros al addeventListener.

Para solucionar la imcompatibilidad en ente navegadores dejo aqui una funcion para añadir eventos:

JAVASCRIPT:
  1. function AnadirEvento(evento, funcion, elemento) {
  2.  
  3. if (elemento.addEventListener)  // standard W3C DOM
  4. return elemento.addEventListener(evento,funcion,false);
  5. else if (elemento.attachEvent) { // IE cabron DOM
  6. return elemento.attachEvent("on"+evento, funcion);
  7. }else{ // resto navegadores
  8. try{
  9. elemento["on"+evento] = funcion;
  10. }
  11. catch(e){throw 'No es posible añadir evento';}
  12. }
  13. }

Etiquetas: , , ,

Un comentario para “funcion con parametros para AddEventListener()”


  1. Deprecated: Function ereg() is deprecated in /home/controlz/public_html/blog/wp-content/plugins/google-analyticator/google-analyticator.php on line 399
    Jose dice:

    Estoy empezando con Javascript y llevaba un día entero atascado justo con esto sin saber cómo apsar variables locales a la función del addEventListener, hasta que he dado con tu articulo.

    Me has alegrado el dia y la semana, ¡muchas gracias!

    Un saludo

Deja un comentario

CAPTCHA Image Audio Version
Reload Image