【问题标题】:How to turn function into jQuery plugin如何把函数变成jQuery插件
【发布时间】:2015-06-03 18:52:19
【问题描述】:

这是我的 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() 中显示它。我究竟做错了什么?谢谢。

【问题讨论】:

    标签: javascript jquery jquery-plugins


    【解决方案1】:

    你快用$代替$.fn,因为$.fn是jQuery原型的别名,它需要一个选择器

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

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

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

    DEMO

    【讨论】:

    • 谢谢,@Satpal。 $ 和 $.fn 有什么区别?
    • @Alex,已经有很好的答案了stackoverflow.com/questions/13604040/…
    • 谢谢,@Satpal。为什么警报没有返回任何内容?
    • @Alex, return results === null ? "" 因为位置没有查询字符串,所以返回空字符串
    【解决方案2】:

    您缺少选择器 $(),因为您正在扩展 $.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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-25
      • 2011-09-09
      • 2018-03-17
      • 2013-10-29
      • 2017-07-01
      相关资源
      最近更新 更多