jQuery扩展函数根据条件保留链接

时间:2014-04-04 10:47:46

标签: javascript jquery

我正在尝试创建一个jquery构建它的函数,它允许我从一个元素或一组元素中更改maxHeight或检索maxHeight。

设置maxHeight:$('.element-class').maxHeight(500);效果很好。 但是,当我不在maxHeight()中传递参数时,我想返回元素的高度,而不是保留jquery可链接性:

来源:

(function($) {

    // jQuery plugin definition
    $.fn.maxHeight = function() {

        var params = arguments;
        var $this = this;
        console.log(params);
        this.each(function() {

            var $t = $(this);

            if (params.length > 0 ) {
                if (params[0] == 'none'){
                    $t.get(0).style.maxHeight = 'none';
                } else {
                    $t.get(0).style.maxHeight = params[0] + 'px';
                }
                return $t;
            } else {
                var h = (($t.get(0).style.maxHeight && $t.get(0).style.maxHeight != '') ? parseInt($t.get(0).style.maxHeight) : 0);
                console.log(h);
                return h;
            }

        });

        return this;
    };

})(jQuery);

1 个答案:

答案 0 :(得分:0)

我认为你必须做一个回调函数,没有时间测试它,但试试这个:

(function($) {

    // jQuery plugin definition
    $.fn.maxHeight = function(a, callback) {

        var $this = this;
        this.each(function() {

            var $t = $(this);

            if (!a) {
                    $t.get(0).style.maxHeight = 'none';
                } else {
                    $t.get(0).style.maxHeight = a + 'px';
                }
                callback($t);
            } else {
                var h = (($t.get(0).style.maxHeight && $t.get(0).style.maxHeight != '') ? parseInt($t.get(0).style.maxHeight) : 0);
                callback(h);
            }

        });
    };

})(jQuery);

然后做这样的事情:

$('.element-class').maxHeight(500 , function(result){


// use your result or not

// Want to chain 
return result;

});
相关问题