如何将函数变成 jQuery 插件

How to turn function into jQuery plugin

这是我的 jsFiddle:http://jsfiddle.net/jsFiddlePlayer/vhg7csb7/10/

我正在尝试将此 Whosebug question 中的答案作为 jQuery 插件实现,但没有成功。 getParameterByName 函数读取 URL 的查询字符串变量和 return 参数中指示的变量。但是,我的代码一直在说:

.getParameterByName is not a function

我的jQuery代码如下:

$(document).ready(function(){
    var paramABC = $.getParameterByName('abc');    
    alert(paramABC);
});

(function ($) {
    /* Gets value of querystring variable by name */
    $.fn.getParameterByName = function (name) {
        name = name.replace(/[\[]/, "\[").replace(/[\]]/, "\]");
        var regex = new RegExp("[\?&]" + name + "=([^&#]*)"),
            results = regex.exec(('http://www.myexample.com/?abc=1&def=2').search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    };
}(jQuery));

请注意,我在上面的函数中硬编码了一个 location,因为 jsFiddle 在 URL 上没有查询字符串变量。该行的原始代码是:

results = regex.exec(location.search);

如果此代码有效,它将 return 1(因为查询字符串中的 abc=1)并将其显示在 alert() 中。我究竟做错了什么?谢谢。

你几乎可以使用 $ 而不是 $.fn,因为 $.fn 是 jQuery 原型的别名,它需要一个选择器

$.getParameterByName = function (name) {
   //
};

注意:先定义插件代码再使用。

读得不错What is the difference between $ and $.fn?

DEMO

您缺少选择器 $(),因为您正在扩展 $.fn

$(document).ready(function(){
    var paramABC = $().getParameterByName('abc');    
    alert(paramABC);
});

(function ($) {
    /* Gets value of querystring variable by name */
    $.fn.getParameterByName = function (name) {
        name = name.replace(/[\[]/, "\[").replace(/[\]]/, "\]");
        var regex = new RegExp("[\?&]" + name + "=([^&#]*)"),
            results = regex.exec(('http://www.myexample.com/?abc=1&def=2').search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    };
}(jQuery));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>