Javascript <;p>;元素出现和消失错误

Javascript <;p>;元素出现和消失错误,javascript,jquery,Javascript,Jquery,下面的#password error元素,会毫无理由地快速消失并再次隐藏。有人知道为什么吗 $(function(){ $('#password-error').hide(); $('#submit').on('click', function(){ if ($('#password').val() != $('#password2').val()){ $('#password-error').show(); } else

下面的
#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();
   //$(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();
     }
   });
});

#submit
是导致表单提交的提交输入吗?是否在验证失败时阻止表单提交?@Stryner不,但我认为这与问题无关。您的第二种方法起作用,但我无法理解这是如何阻止
$(“#密码错误”)的
elemets的功能您正在收听表单上的
submit
事件。在事件对象(
event
)上,有一个方法将阻止该表单的默认功能(正在提交)
event.preventDefault()
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();
     }
   });
});