带原型函数的递归

时间:2013-11-10 11:37:46

标签: javascript jquery recursion prototype

我想创建一个新的jQuery函数,我可以在该函数中传递一个或多个值。然后,对于DOM的所有匹配元素,迭代所有不同的选项,但一次只能选择一个选项。因此,对于未处理的所有元素,重放原型函数。所有的处理应该是相同的功能,所以我想在递归,但因为我不是真的经验javascript中的原型,我不知道如何做到这一点。 现在,没有错误,但甚至没有任何事情发生。

这是对的吗?

感谢您的启发。

(function($) {
    $.fn.foo = function (prop) {
        var options = $.extend({
            "elt" : "",   // Declaration of my options
            "callback" : function(){}
        }, prop)

        var optionsTab = options.elt.split('#');
        var current = optionsTab.slice(0,1),
        var remaining = optionsTab.slice(1);
        var result = this.each(function() {
            var el = $(this);
            // Code handling the first element in the option
        });

        if (remaining.length > 0) {
            $({ "elt": remaining.join("#") }); // Trial of recursion of foo
            return result;
        }
    }

2 个答案:

答案 0 :(得分:0)

我认为你正试图在超时时递归调用我是否正确?

    var result = this.each(function() {
        var el = $(this);
        // Code handling the first element in the option
    });

    if (remaining.length > 0) {
        $({ "elt": remaining.join("#") }); // Trial of recursion of foo
       var me = this;
       setTimeout(function(){
         me.foo(parameters);//not sure what the parameters should be
       },500);
    }
    return this;

一些有用的信息:https://stackoverflow.com/a/16063711/1641941(在“此变量”下)

答案 1 :(得分:0)

创建this fiddle并且它有效:

$.fn.foo = function (prop) {
    var options = $.extend({
        "elt" : "",   // Declaration of my options
        "callback" : function(){}
    }, prop);

    var optionsTab = options.elt.split('#');
    var current = optionsTab.slice(0,1);
    var remaining = optionsTab.slice(1);
    this.each(function() {
        var el = $(this);
        // Code handling the first element in the option
    });

    if (remaining.length > 0) {
        this.foo({ "elt": remaining.join("#") }); // Trial of recursion of foo
    }
    return this;
};
相关问题