2013-10-22 35 views
2

很簡單的例子,當我使用「需要」內部功能,應該在實際的表單驗證運行,但它也確實在頁面加載執行運行功能。jQuery驗證 - 裏面怎麼「需要」但不執行負載

的問題是,如何避免它,並因此它會叫裏面只有實際驗證所需的其他功能。

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

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

回答

1

你需要用另一個函數內部函數調用:

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

這樣做的原因是因爲從runFunction返回值被設置爲在加載required屬性的值。通過上面的代碼,您將爲required屬性分配一個函數,該函數僅在驗證時運行。在required callback

+0

我明白了,在這種情況下,你認爲我能避免增加額外的功能,爲每路輸入,只是驗證一羣人喜歡: $( 「輸入[名稱= testinput],輸入[名稱= testinput2],輸入[名稱= testinput3]」)。每個(函數(){ \t \t $(本).rules( 「添加」,{ \t \t \t required:function(element){runFunction(' hello world')} \t \t}); \t \t}); – devjs11

+0

該方法也應該起作用,儘管我沒有看到將這些規則放在'validate()'初始化中的問題。 –

+0

謝謝你,唯一的問題是,我有太多的輸入,將會是什麼樣子: testinput:{要求:功能(EL){runFunction(「世界你好」)}} testinput2:{要求:功能(EL ){runFunction( '的hello world')}} testinput3:{需要:功能(EL){runFunction( '的hello world')}} testinput4:{需要:功能(EL){runFunction( '的hello world')} } 等 – devjs11

1

通話功能,

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

required-method

1

另一種方法是使用某種局部應用的

看也許:然後Partial Application - Eloquent 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

+0

感謝您的額外幫助。 – devjs11