如何创建一个返回bool的jQuery函数?

时间:2010-08-13 20:22:13

标签: jquery

如何创建像

这样的jQuery函数
$.MyFunction(/*optional parameter*/)?

会返回一个bool?

注意:

我试过这个:

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;
    });
});

但它在使用

的alert()时崩溃了
Microsoft JScript runtime error: Object doesn't support this property or method

这最终有效:

jQuery.isValidRequest = function (options) {

    return true;
}

5 个答案:

答案 0 :(得分:5)

对于您打算从jQuery 实例调用的函数,您可以这样定义:

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

并像其他任何jQuery方法一样调用:

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

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

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

并以同样的方式打电话:

$.MyFunction(...);

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

(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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

$.myfunction(options){
return options.isThisTrue;
}

用法:

       $(document).ready(function(){ 
         var isThisTrue = $.myfunction({isthisTrue: false});
         // isThisTrue is false
        });

答案 3 :(得分:0)

$。fn.MyFunction = function(params){return true; }

答案 4 :(得分:0)

$.fn.MyFunction = function(param) {
   if(arguments.length > 0)
      return true;
   else
      return false;
}