【问题标题】:jQuery : snackbar : append() element,add css by class and then remove() it with delayjQuery:snackbar:追加()元素,按类添加css,然后延迟删除()它
【发布时间】:2018-08-23 22:35:16
【问题描述】:

我创建了一个包含多个输入的表单,其中一个是“全名”,当然最后还有一个提交按钮。

函数检查名称输入是否仅为字母字符, 如果为真,它将追加 div 元素,添加 css 类, 小吃吧会淡入淡出,最后消失。 以下代码有什么问题:

$(document).ready(function(){
$(".submitForm").click(function(){
    var fullname = $("#firstName").value; 
    var checkIfTrue = /^[A-Za-z ]+$/.test(fullname);
    if (checkIfTrue==true) {
        $('body').append("<div id='textBox'> some text</div>"); 
        $("#textBox").addClass("showPopup");
        setTimeout(function(){
            $("#textBox").remove();}, 3000); 
        return true;
    } 
    else {
        alert("wrong input");
        return false;
    }   
})
})

还有相关的css:

.showPopup {
  visibility : visible;
  animation : fadein 0.5s, fadeout 0.5s 2.5s;
}

@keyframes fadein {
  from {bottom: 0; opacity: 0;}
  to {bottom: 20px; opacity: 1;}
}

@keyframes fadeout {
  from {bottom: 20px; opacity: 1;}
  to {bottom: 0; opacity: 0;}
}

干杯 (我自己无法弄清楚: jQuery: append() object, remove() it with delay())

【问题讨论】:

    标签: jquery


    【解决方案1】:

    有一些小问题,比如使用.value (vanilla JS) 而不是.val() (jQuery)...

    当然还有主要问题,即按钮单击时的提交预防。见.preventDefault()

    其余的见代码中的 cmets:

    $(document).ready(function(){
      $(".submitForm").click(function(event){
        event.preventDefault();  // Prevent the submit behavior of the button
    
        var fullname = $("#firstName").val(); // .val() instead of .value
        var checkIfTrue = /^[A-Za-z ]+$/.test(fullname);
        if (checkIfTrue) {  // No need for the ==true
          $('body').append("<div id='textBox'> some text</div>"); 
          $("#textBox").addClass("showPopup");
          setTimeout(function(){
            $("#textBox").remove();
            $(this).closest("form").submit();  // Since it's ok and the animation's over... Submit the form.
          }, 3000); 
          //return true;  // No need to return anything from an event handler
        } 
        else {
          alert("wrong input");
          //return false;  // No need to return anything from an event handler
        }   
      })
    })
    

    【讨论】:

      猜你喜欢
      • 2014-02-14
      • 2011-04-09
      • 2016-09-10
      • 2021-04-05
      • 2011-03-09
      • 1970-01-01
      • 2012-10-06
      • 2017-05-06
      • 1970-01-01
      相关资源
      最近更新 更多