我想提出一個表單驗證功能提交表格,如果沒有空輸入的按鈕需要兩次點擊才能正常工作。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');
任何想法將是巨大的,也是關於如何縮短/提高代碼的建議。
什麼是預期的行爲? –
在if(isEmpty){...}塊內設置'event.preventDefault()'。無需返回聲明或解除點擊事件 –
'error = error || '錯誤';'和'error =錯誤一樣嗎?錯誤:「錯誤」;' – tewathia