0
HTML下方&用于表单提交的JS。这可以正常工作。Jquery - 通过循环表单字段JS代码
但是,我想通过使用任何循环迭代最小化JS代码长度。
在'全名'&'Booking Ref no。'之间。只有ID &类名称正在改变。剩余的JS脚本是相同的。
是否有可能通过使用任何循环迭代使JS代码干净?
感谢
HTML:
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6 fullname">
<div class="form-title">Full name</div>
<input type="text" name="Full Name" id="fullname" data-fullname="Full name is missing">
</div>
<div class="col-lg-6 col-md-6 col-sm-6 bookingrefno">
<div class="form-title">Booking reference number</div>
<input type="text" name="Booking Reference Number" id="bookingrefno" data-refno="Booking Reference No. is not valid">
</div>
</div>
JS:
/* Full Name*/
$('#fullname').focus(function(){
$('.fullname .form-title').addClass('input-filled');
$(this).addClass('input-focused');
$(this).removeClass('has-error');
$(this).parent().find('.form-title').removeClass('has-error');
});
$('#fullname').blur(function(){
if($('#fullname').val() == ''){
$('.fullname .form-title').removeClass('input-filled');
$(this).removeClass('input-focused');
} else {
$('.fullname .form-title').addClass('input-filled');
$(this).addClass('input-focused');
}
});
$('.fullname .form-title').click(function(){
$(this).addClass('input-filled');
$('#fullname').addClass('input-focused');
});
/* Ref No */
$('#bookingrefno').focus(function(){
$('.bookingrefno .form-title').addClass('input-filled');
$(this).addClass('input-focused');
$(this).removeClass('has-error');
$(this).parent().find('.form-title').removeClass('has-error');
});
$('#bookingrefno').blur(function(){
if($('#bookingrefno').val() == ''){
$('.bookingrefno .form-title').removeClass('input-filled');
$(this).removeClass('input-focused');
} else {
$('.bookingrefno .form-title').addClass('input-filled');
$(this).addClass('input-focused');
}
});
$('.bookingrefno .form-title').click(function(){
$(this).addClass('input-filled');
$('#bookingrefno').addClass('input-focused');
});
你可以声明一个数组'a = ['bookingrefno','fullname']'并迭代它。 您可以将通用代码声明为函数,并使用数组中的每个元素调用该函数 –