欢迎留言

// 表单验证 $("#contactForm").on("submit", function(e) { e.preventDefault(); var isValid = true; // 重置错误提示 $(".error-message").hide(); // 验证姓名 if ($("#name").val().trim() === "") { $("#nameError").show(); isValid = false; } // 验证电话 var phonePattern = /^1[3-9]\d{9}$/; if (!phonePattern.test($("#phone").val())) { $("#phoneError").show(); isValid = false; } // 验证内容 if ($("#content").val().trim() === "") { $("#contentError").show(); isValid = false; } if (isValid) { // 提交表单 $.ajax({ url: $(this).attr("action"), type: "POST", data: $(this).serialize(), dataType: "json", success: function(response) { if (response.code === 1) { // 提交成功 $("#successMessage").show(); $("#contactForm")[0].reset(); // 3秒后隐藏成功提示 setTimeout(function() { $("#successMessage").fadeOut(); }, 3000); } else { // 提交失败 $("#submitError").text(response.msg || "提交失败,请稍后再试"); $("#submitError").show(); // 3秒后隐藏错误提示 setTimeout(function() { $("#submitError").fadeOut(); }, 3000); } }, error: function() { // 网络错误 $("#submitError").text("网络错误,请稍后再试"); $("#submitError").show(); // 3秒后隐藏错误提示 setTimeout(function() { $("#submitError").fadeOut(); }, 3000); } }); } }); // 输入框获得焦点时隐藏错误提示 $("input, textarea").on("focus", function() { $(this).next(".error-message").hide(); }); });