2016-09-28 19 views
1

我想提出一個表單驗證功能提交表格,如果沒有空輸入的按鈕需要兩次點擊才能正常工作。jQuery的:按鍵僅經過兩次點擊

這是我的函數:

function validate(root, animation, error) { 
    $('.button').on('click', function(event) { 
     event.preventDefault() 

     var isEmpty = false, 
      root  = $(root), 
      animation = animation ? animation : 'animation animation-shake', 
      error  = error ? error : 'error'; 

     root.find('form').find('.required').each(function() { 
      if ($(this).val().length == 0) { 
       isEmpty = true; 
       root.addClass(animation); 
       $('.required.error:first').focus(); 
       $(this).addClass(error).on('keydown', function() { 
        $(this).removeClass(error); 
        root.removeClass(animation); 
       }); 
      } 
     }); 

     if (isEmpty) return; 
     $(this).unbind('click'); 
    }); 
} 

調用該函數的代碼:

validate('#login-box .box'); 

任何想法將是巨大的,也是關於如何縮短/提高代碼的建議。

+0

什麼是預期的行爲? –

+3

在if(isEmpty){...}塊內設置'event.preventDefault()'。無需返回聲明或解除點擊事件 –

+1

'error = error || '錯誤';'和'error =錯誤一樣嗎?錯誤:「錯誤」;' – tewathia

回答

2

你的方法應該是:

function validate(root, animation, error) { 
    $('.button').on('click', function(event) { 
     /* event.preventDefault();*/ //<< remove it 
     var isEmpty = false, 
      /*...*/ 
     /*if (isEmpty) return; 
      $(this).unbind('click');*/ //<< remove it 

     // and set at handler bottom 
     if (isEmpty) event.preventDefault(); 
    }); 
} 

只有防止在需要時提交的行爲。

0

您驗證功能,這就是爲什麼它需要2次點擊 首先點擊結合的Click事件,然後第二次點擊觸發裏面代碼中click事件綁定到按鈕。 從代碼中點擊刪除事件。

+0

甚至在這是一個函數之前,結果是一樣的。 –

+0

它說「validate(..)'是從點擊按鈕被調用的? –

+0

@ freedomn-m。我想$點擊()函數驗證裏面添加...請檢查,如果我沒有錯 – Developer