1 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊
該塊中的最后一行刪除了錯(cuò)誤表單類,并將 OK 表單類添加回來(lái),使您嘗試添加的行本質(zhì)上是無(wú)操作:
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');
}
事實(shí)上,如果您在調(diào)試器中單步執(zhí)行代碼,您將看到類切換,然后在到達(dá)塊末尾時(shí)切換回來(lái)。
有很多方法可以解決這個(gè)問(wèn)題。一種方法是在該塊中保留一個(gè)布爾值,然后根據(jù)最后的值設(shè)置類:
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');
? ? }
}
添加回答
舉報(bào)