我正在学习 javascript 和 jquery,我编写了以下代码来检查表单的某些输入是否已填充,如果是,它们会获得特殊的样式。
代码工作正常,但我想知道编写此代码的最佳方法是什么,也许它可以更短?
$(document).ready(function () {
$("#id_email").change(function () {
var emailField = document.getElementById("id_email").value;
if (emailField.indexOf("@") >= 0 && emailField.indexOf(".") >= 0) {
$(this).attr( /* styling my field */ );
} else {
$(this).attr( /* styling my field */ );
}
});
$("#id_last_name").change(function () {
var nameField = document.getElementById("id_last_name").value;
if (nameField.length > 0) {
$(this).attr( /* styling if true */ );
} else {
$(this).attr( /* styling if false */ );
}
});
$("#id_phone").change(function () {
var phoneField = document.getElementById("id_phone").value;
if (phoneField.length > 0) {
$(this).attr( /* styling if true */ );
} else {
$(this).attr( /* styling if false */ );
}
});
$("#id_company").change(function () {
var companyField = document.getElementById("id_company").value;
if (companyField.length > 0) {
$(this).attr( /* styling if true */ );
} else {
$(this).attr( /* styling if false */ );
}
});
$("#id_activity").change(function () {
var activityField = document.getElementById("id_activity").value;
if (activityField !== "---------") {
$(this).attr( /* styling if true */ );
} else {
$(this).attr( /* styling if false */ );
}
});
});
最佳答案
您可以使用简写 if 语句并使用 $(this).val()
而不是 document.getElementById("").value;
:
$(document).ready(function() {
$("#id_email").change(function() {
var emailField = $(this).val();
(emailField.indexOf("@") >= 0 && emailField.indexOf(".") >= 0) ? $(this).attr( /* styling my field */ ) : $(this).attr( /* styling my field */ );
});
$("#id_last_name").change(function() {
var nameField = $(this).val();
(nameField.length > 0) ? $(this).attr( /* styling if true */ ) : $(this).attr( /* styling if false */ );
});
$("#id_phone").change(function() {
var phoneField = $(this).val();
(phoneField.length > 0) ? $(this).attr( /* styling if true */ ) : $(this).attr( /* styling if false */ );
});
$("#id_company").change(function() {
var companyField = $(this).val();
(companyField.length > 0) ? $(this).attr( /* styling if true */ ) : $(this).attr( /* styling if false */ );
});
$("#id_activity").change(function() {
var activityField = $(this).val();
(activityField !== "---------") ? $(this).attr( /* styling if true */ ) : $(this).attr( /* styling if false */ );
});
});
关于javascript - 简单的实时 jquery 表单验证器的代码结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41833211/