用于普通函数的jQuery方法执行?

时间:2013-10-29 17:03:02

标签: javascript jquery

我有一个很好的jQuery链:

$(...)
    .method1()
    .method2()
    .method3()
    ...;

现在,我发现我希望将.method2()替换为运行.method2a().method2b(p1)的条件。事实上,我想这样做:

$(...)
    .method1();

if (cond)
    $(...).method2a()
else
    $(...).method2b(p1)

$(...)
    .method3()
    ...;

但这很难看 - 它打破了美丽的链条!

所以我正在寻找允许我在链中运行自己的函数的jQuery API方法XYZ!所以它看起来像这样:

$(...)
    .method1()
    .XYZ(function () {
        if (cond)
            this.method2a()
        else
            this.method2b(p1);
    })
    .method3()
    ...;

那么,是否有任何jQuery方法XYZ可以允许这个?与此最接近的是.each,但我不喜欢为每个元素单独运行它!

2 个答案:

答案 0 :(得分:5)

我真的很讨厌我要告诉你的事情,我觉得它很难看,但你可以用这个:

$(...)
.method1()
[cond ? 'method2a' : 'method2b']()
.method3();

第二个解决方案:

将此代码添加到您的文件

(function($){
    if(!$.fn.if)
        $.fn.if = function(cond, trueFn, falseFn){
            if(cond)
                trueFn.call(this);
            else
                falseFn.call(this);

            return this
        }
})(jQuery)

编辑:格式化

这将使您可以访问函数.if(),可以像这样使用:

$('body').if(cond, 
         function(){
             this.addClass('a')
         },
         function(){
             this.addClass('b')
         })

答案 1 :(得分:1)

我不知道内置的内容,但这是一个非常简单的插件:

(function() {

    $.fn.XYZ = function(fn) {
        fn.call(this);
        return this;
    }; 

} ());