2

非常简单的示例,当我在“必需”中使用应该在实际表单验证上运行但它也在页面加载时执行的函数时。

问题是如何避免它并使其仅在实际验证时才调用内部所需的其他函数。

$("form").validate({           
            rules : {
                testinput: {
                    required: runFunction('hello world')
                }
});

function runFunction(a){
    console.log(a);
}
4

3 回答 3

1

您需要将函数调用包装在另一个函数中:

$("form").validate({           
    rules : {
        testinput: {
            required: function(el) {
                runFunction('hello world')
            }
        }
    });
});

这是因为返回的值runFunction被设置为required加载时属性的值。使用上面的代码,您正在为属性分配一个函数,该函数required仅在验证时运行。

于 2013-10-22T11:49:20.463 回答
1

required callback在like中调用函数,

$("form").validate({           
    rules : {
        testinput: {
             required: function(){ runFunction('hello world'); 
        }
    }
});

阅读所需方法

于 2013-10-22T11:52:05.587 回答
1

另一种方法是使用某种部分应用程序

或许可以看看:部分应用程序 - Eloquent Javascript

然后,您的代码可能会出现在以下几行中:

$("form").validate({           
    rules : {
        testinput: {
            required: partial(runFunction,'hello world')
        }
});

Wherepartial(runFunction,'hello world')创建了一个新函数,它等效于 runFunction('hello world')。

这是函数式编程的一个强大概念,并且可以扩展 JS 来支持这样的事情。

编辑:1可能是对部分应用的更好解释

http://www.drdobbs.com/open-source/currying-and-partial-functions-in-javasc/231001821

于 2013-10-22T11:59:51.863 回答