如何将函数转换为jQuery插件

时间:2015-06-03 18:52:19

标签: javascript jquery jquery-plugins

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

我正在尝试将此StackOverflow question中的答案作为jQuery插件实现并且没有运气。 getParameterByName函数读取URL的查询字符串变量并返回参数中指示的变量。但是,我的代码一直在说:

  

.getParameterByName不是函数

我的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);

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

2 个答案:

答案 0 :(得分:4)

你几乎使用SELECT * FROM postcodes WHERE ABS(latitude - @lat) < 50 AND ABS(longitude - @lng) < 50 而不是filter(ReplaceTokens, tokens: [VERSION : project.version]) ,因为$是jQuery原型的别名,它需要一个选择器

$.fn

注意:首先定义插件代码然后使用它。

好读What is the difference between $ and $.fn?

DEMO

答案 1 :(得分:0)

由于您要扩展$()

,因此您缺少选择器$.fn

&#13;
&#13;
$(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));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

相关问题