How to edit jquery function

I am trying to change the attr function in jQuery core (V.6.1).

I have a plugins.js file that is included in the page after the jquery-6.1.js file. The plugins.js file contains improvements made to various basic jQuery functions to accommodate some SVG functions.

I copied the attr function to the plugins.js file without modifying it, but now it causes a JavaScript error when it is called.

Does anyone know why this particular function does not like overwriting (I probably rewrite it wrong):

(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); 
+6
source share
1 answer

Instead of completely rewriting the base attr function, just do it like this:

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

I did something like this to override $.each to provide some custom functions. I'm not sure if this will fix the error you have, but this is the best way to add minor custom changes to the functionality, rather than copy / paste the whole method to make one change. This method also allows you to modify the jQuery core library without affecting your setup.

+7
source

Source: https://habr.com/ru/post/891551/


All Articles