jQuery Validate - 如何在“必需”中运行函数而不在加载时执行它

jQuery Validate - how to run function inside "required" without executing it on load

本文关键字:函数 加载 执行 运行 Validate jQuery 必需      更新时间:2023-09-26

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

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

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

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

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

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

调用

函数,required callback像,

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

读取所需方法

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

也许看到: 部分应用程序 - 雄辩的Javascript

然后,您的代码可能是以下行中的内容:

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

其中partial(runFunction,'hello world')创建一个与runFunction('hello world')相同的新函数。

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

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

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