javascript - 覆盖 jquery.param 函数

标签 javascript jquery

我对 jQuery.param 函数有疑问。 jQuery 使用 + 而不是 %20 来对 URL 编码空格

var obje = {
    'test': 'tester 2'
}
console.log($.param(obje));

返回“test=tester+2”

所以我考虑重写这个核心函数:

(function($){
        $.fn.param = function( a, traditional ) {
            console.log('custom $.param');
            var s = [],
                add = function( key, value ) {
                    // If value is a function, invoke it and return its value
                    value = jQuery.isFunction( value ) ? value() : value;
                    s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
                };

            // Set traditional to true for jQuery <= 1.3.2 behavior.
            if ( traditional === undefined ) {
                traditional = jQuery.ajaxSettings.traditional;
            }

            // If an array was passed in, assume that it is an array of form elements.
            if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
                // Serialize the form elements
                jQuery.each( a, function() {
                    add( this.name, this.value );
                } );

            } else {
                // If traditional, encode the "old" way (the way 1.3.2 or older
                // did it), otherwise encode params recursively.
                for ( var prefix in a ) {
                    buildParams( prefix, a[ prefix ], traditional, add );
                }
            }
            return s.join("&");
            // Return the resulting serialization
            //return s.join( "&" ).replace( r20, "+" );
        };
    })(jQuery);
var obje = {
    'test': 'tester 2'
}
console.log($.param(obje));

然而这失败了.. $.param 没有被覆盖。

知道哪里出了问题吗?

谢谢!

编辑:我的解决方案(因为我是新用户,我可能无法在 8 小时内回答我自己的问题(这是为什么?))

使用 ThiefMaster 的解决方案,我仍然遇到 buildParams 未定义的问题。 我通过调用旧函数解决了这个问题,然后将 + 替换回 %20

// modification of the jQuery.param function: spaces are encoded by jQuery.param with + instead of %20. replace these back to %20
(function($, oldFunction){
    $.param = function( a, traditional ) {
        var s = oldFunction.apply(oldFunction,[a,traditional]);
        // Return the resulting serialization
        return s.replace( '+', '%20' );
    };
})(jQuery,jQuery.param);

最佳答案

您需要使用 $.param 而不是 $.fn.param (这将是一个调用 jQuery 对象的函数,例如 $( ...).param()).

关于javascript - 覆盖 jquery.param 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5804872/

相关文章:

javascript - 如何在 div 中拖放和缩放图像并保持相同的大尺寸?

javascript - 使用javascript从输入框中获取值

javascript - 我安装了错误的 NPM 包。我应该担心吗?

javascript - 自动完成单词的任何部分

jquery - html css拖放文件上传样式

javascript 删除函数无效

javascript - 如何在选择器中引用 SharePoint 属性?

javascript - YUI 3 上传 - 选择文件按钮离线时不显示

javascript - 使用javascript循环遍历fileList

javascript - 如何计算图像纵横比的高度/宽度