追加span元素和fadeOut jQuery

时间:2017-02-23 13:13:25

标签: javascript jquery html fadeout

我正在为只接受数字的输入字段开发验证函数。如果它不是一个数字,则会通过以下消息附加一个跨度:"只有数字"然后淡出。问题是输入字段和跨度都消失了。

如何才能使消息淡出?

</head>
<body id="test">
Number : <input type="text" title="numInput" name="quantity" id="quantity"   maxlength="8" />&nbsp;

</body>
</html>

的jQuery

$(document).ready(function () {

$('input[title="numInput"]').keypress(function (e) {
 //if the letter is not digit then display error and don't type anything
 if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {

var errmsg = "<span>Only digits</span>";

  $("#test").append(errmsg).show().fadeOut("slow");
           return false;
 }

 });
});

1 个答案:

答案 0 :(得分:1)

$(document).ready(function() {

  $('input[title="numInput"]').keypress(function(e) {
    //if the letter is not digit then display error and don't type anything
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {

      $(".error").fadeIn("slow").fadeOut("slow");
      return false;
    }

  });
});
.error{display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body id="test">
  Number : <input type="text" title="numInput" name="quantity" id="quantity" maxlength="8" />&nbsp;
<span class="error">Only digits</span>
</body>

  1. 在html中添加错误消息span
  2. 将类添加到span,然后将其隐藏在CSS
  3. 然后做fadein和fadeout
  4. $(document).ready(function() {
    
      $('input[title="numInput"]').keypress(function(e) {
        //if the letter is not digit then display error and don't type anything
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
    
          var errmsg = "<span id='spantoremove'>Only digits</span>";
          var thiscontext = $(this);
    
          $('#test').append(errmsg);
          setTimeout(function() {
            $("#spantoremove").remove()
          }, 3000);
          return false;
        }
    
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <body id="test">
      Number : <input type="text" title="numInput" name="quantity" id="quantity" maxlength="8" />&nbsp;
    </body>

    1. 尝试使用settimeout。
    2. 在附加settimeout示例3秒后删除