2011-06-28 10 views
6

Estoy tratando de modificar la función 'attr' en el núcleo de jQuery (V.6.1).Cómo editar una función jquery

Tengo un archivo plugins.js que se incluye en la página después del archivo jquery-6.1.js. El archivo plugins.js contiene mejoras hechas a varias funciones centrales de jQuery para acomodar algunas funciones de SVG.

He copiado la función attr en el archivo plugins.js sin modificarlo, pero ahora produce un error de JavaScript cuando se invoca.

¿Alguien sabe por qué esta función en particular no le gusta ser sobrescritos (Probablemente estoy sobreescribiéndolo de la manera equivocada):

(function($){ 

    $.fn.attr = function(elem, name, value, pass){ 

     var nType = elem.nodeType; 

     // don't get/set attributes on text, comment and attribute nodes 
     if (!elem || nType === 3 || nType === 8 || nType === 2) { 
      return undefined; 
     } 

     if (pass && name in jQuery.attrFn) { 
      return jQuery(elem)[ name ](value); 
     } 

     // Fallback to prop when attributes are not supported 
     if (!("getAttribute" in elem)) { 
      return jQuery.prop(elem, name, value); 
     } 

     var ret, hooks, 
      notxml = nType !== 1 || !jQuery.isXMLDoc(elem); 

     // Normalize the name if needed 
     name = notxml && jQuery.attrFix[ name ] || name; 

     hooks = jQuery.attrHooks[ name ]; 

     if (!hooks) { 

      // Use boolHook for boolean attributes 
      if (rboolean.test(name) && 
       (typeof value === "boolean" || value === undefined || value.toLowerCase() === name.toLowerCase())) { 
       hooks = boolHook; 

      // Use formHook for forms and if the name contains certain characters 
      } else if (formHook && (jQuery.nodeName(elem, "form") || rinvalidChar.test(name))) { 
       hooks = formHook; 
      } 

     } 

     if (value !== undefined) { 

      if (value === null) { 
       jQuery.removeAttr(elem, name); 
       return undefined; 

      } else if (hooks && "set" in hooks && notxml && (ret = hooks.set(elem, value, name)) !== undefined) { 
       return ret; 

      } else { 
       elem.setAttribute(name, "" + value); 
       return value; 
      } 

     } else if (hooks && "get" in hooks && notxml) { 

      return hooks.get(elem, name); 

     } else { 

      ret = elem.getAttribute(name); 

      // Non-existent attributes return null, we normalize to undefined 
      return ret === null ? 
       undefined : 
       ret; 
     } 

    }; 

})(jQuery); 
+2

¿Qué error produce? –

+2

¿qué tipos de elementos está usando attr on? en jquery 1.6 cambiaron de forma exclusiva cómo funciona attr, ahora usa prop en ciertos elementos html como etiquetas DIV y tablas para establecer propiedades: http://api.jquery.com/prop/ – John

+0

Elem operando 'in' inválido - if (! ("getAttribute" en elem)) { Incidentially, he usado esta técnica antes para modificar partes de jQuery, simplemente parece ser la función attr (hasta ahora) que no acepta la sobreescritura. – Steve

Respuesta

7

En lugar de sobrescribir por completo la función de base attr, simplemente extenderlo de esta manera:

(function($){ 
    var jqAttr = $.fn.attr; 
    $.fn.attr = function(elem, name, value, pass) { 
     // check to see if it's the special case you're looking for 
     if (name === 'transform') { 
      // handle your special SVG case here 
     } else { 
      jqAttr(elem, name, value, pass); 
     } 
    }; 
}(jQuery)); 

hice algo similar a esto para anular $.each proporcionar alguna funcionalidad personalizada. No estoy seguro de si esto solucionará el error que está teniendo, pero es una mejor manera de agregar un pequeño cambio personalizado en la funcionalidad en lugar de tener que copiar/pegar todo el método para hacer un cambio. Este método también permite que la biblioteca jQuery base cambie sin afectar su personalización.

+0

Me gusta. Gracias por el buen consejo. – Steve

+0

BTW: Esto se llama "parche de monos". – Axel

Cuestiones relacionadas