1 回答

TA貢獻1772條經驗 獲得超5個贊
該塊中的最后一行刪除了錯誤表單類,并將 OK 表單類添加回來,使您嘗試添加的行本質上是無操作:
else if (validateAddress($(this).val())) {
? ? if (!$(this).val().match(/\d+/)) {
? ? ? ? // we try swapping classes
? ? ? ? $(this).removeClass('ok-form').addClass('error-form');
? ? ? ? if (!$(this).parent().find('.warningsmall').length)
? ? ? ? ? ? $(this).parent().append('<span class="warningsmall">' + street_number_warning + '</span>');
? ? } else {
? ? ? ? $(this).parent().find('.warningsmall').remove();
? ? }
? ? // this line undoes the class changes
? ? $(this).removeClass('error-form').addClass('ok-form');
}
事實上,如果您在調試器中單步執行代碼,您將看到類切換,然后在到達塊末尾時切換回來。
有很多方法可以解決這個問題。一種方法是在該塊中保留一個布爾值,然后根據最后的值設置類:
else if (validateAddress($(this).val())) {
? ? let isErrorState = false;
? ? if (!$(this).val().match(/\d+/)) {
? ? ? ? isErrorState = true;
? ? ? ? if (!$(this).parent().find('.warningsmall').length)
? ? ? ? ? ? $(this).parent().append('<span class="warningsmall">' + street_number_warning + '</span>');
? ? } else {
? ? ? ? $(this).parent().find('.warningsmall').remove();
? ? }
? ? // swap classes
? ? if (isErrorState) {
? ? ? ? $(this).removeClass('ok-form').addClass('error-form');
? ? }
? ? else {
? ? ? ? ?$(this).removeClass('error-form').addClass('ok-form');
? ? }
}
添加回答
舉報