& lt; p>元素出现和消失错误

<p> element appear and disappear error

本文关键字:错误 消失 元素 lt      更新时间:2023-09-26

下面的#password-error元素,在没有任何原因的情况下快速淡出并再次隐藏。有人知道为什么吗?

$(function(){
     $('#password-error').hide();
     $('#submit').on('click', function(){
     if ($('#password').val() != $('#password2').val()){
          $('#password-error').show();
     }
     else{
          $('#password-error').hide();
     }
     });
});

如果#submit是表单中的按钮,您必须确保防止表单的默认行为(表单提交):

jQuery(function($) {
   $('#password-error').hide();
   $('#submit').on('click', function(event) {
     if ($('#password').val() != $('#password2').val()) {
       $('#password-error').show();
       event.stopPropagation(); // Stops the event to bubble to the form
     }
     else {
       $('#password-error').hide();
     }
   });
});

您可能需要考虑将侦听器直接绑定到表单上,以确保即使用户在字段中按下enter键也会触发验证:

jQuery(function($) {
   $('#password-error').hide();
   //$(myForm).on('submit', function(event) {
   $('#submit').closest('form').on('submit', function(event) {
     if ($('#password').val() != $('#password2').val()) {
       $('#password-error').show();
       event.preventDefault(); // Prevent the default behavior of the form.
     }
     else {
       $('#password-error').hide();
     }
   });
});