代码之家  ›  专栏  ›  技术社区  ›  DaveDev

如何创建jQuery函数来返回bool?

  •  2
  • DaveDev  · 技术社区  · 14 年前

    如何创建jQuery函数,如

    $.MyFunction(/*optional parameter*/)?
    

    哪一个会返回布尔值?

    我试过这个:

    jQuery.fn.isValidRequest = function (options) {
    
        return true;
    }
    
    // I'm contending with Prototype, so I have to use this    
    jQuery(document).ready(function ($) {    
    
        // and jQuery 1.2.6, supplied by the client - long story
        $('a').livequery('click', function () {
    
            alert($.isValidRequest("blah"));
            return false;
        });
    });
    

    Microsoft JScript runtime error: Object doesn't support this property or method
    

    这就是最终成功的原因:

    jQuery.isValidRequest = function (options) {
    
        return true;
    }
    
    5 回复  |  直到 14 年前
        1
  •  5
  •   Shog9    14 年前

    对于要从jQuery调用的函数 实例

    $.fn.MyFunction = function(options)
    {
      // return bool here
    };
    

    $('selector').MyFunction(...);
    

    要从全局jQuery对象(或其$alias)调用的函数将直接附加到该对象:

    $.MyFunction = function(options)
    {
      // return bool here
    };
    

    $.MyFunction(...);
    

    请注意,为了简洁起见,我使用了$.fn—如果为了与其他库兼容而阻止jQuery使用$别名,这可能会导致问题。附加插件函数的推荐方法是:

    (function($) // introduce scope wherein $ is sure to equate to jQuery
    { 
      $.fn.MyFunction = function(options) 
      { 
        // return bool here 
      };
    })(jQuery); // conclude plugin scope
    

    还要注意,大多数jQuery函数返回 this ,以启用链接;如果选择返回其他值,则无法执行此操作。一定要清楚地记录你的函数返回一个布尔值,否则你会发现自己在想为什么。 $("...").MyFunction().hide() 以后休息。

    您可以在此处阅读有关扩展jQuery的更多信息:
    Extending jQuery – plugin development
    在jQuery文档中:
    Plugins/Authoring

        2
  •  0
  •   Lloyd    14 年前

    http://blogs.microsoft.co.il/blogs/basil/archive/2008/09/22/defining-your-own-functions-in-jquery.aspx

    对于布尔参数,仍然可以像普通JavaScript一样返回true/false。

        3
  •  0
  •   pixeline    14 年前
    $.myfunction(options){
    return options.isThisTrue;
    }
    

           $(document).ready(function(){ 
             var isThisTrue = $.myfunction({isthisTrue: false});
             // isThisTrue is false
            });
    
        4
  •  0
  •   John Strickler    14 年前

    $.fn.MyFunction =函数(params){返回true;}

        5
  •  0
  •   Ian Henry    14 年前
    $.fn.MyFunction = function(param) {
       if(arguments.length > 0)
          return true;
       else
          return false;
    }