jQuery AJAX:如何附加“SAVED”消息并使其在一秒钟后消失

时间:2009-08-16 05:57:18

标签: jquery append fadeout

对于jQuery专家来说,这可能非常简单。

我有< div id =“form23”>< form>< textarea> blahblah< / textarea>< input type =“button”value =“save”onClick =“saveCaption(23)”&gt ;< /形式>< / DIV>

我希望SAVED消息出现并消失。但我不想让表格或其元素消失。

我有一个类似以下的AJAX调用。

function saveCaption(id) {

var queryString = $('#form'+id).formSerialize(); 

  $.ajax({

    type: "POST",

    url: "includes/ajax.php?request=saveCaption",

    data: queryString,

    success: function(response) {

      $('#form'+id).append(response)

    }

  });

  return false;

}

我想知道..我可以追加回复。但有一种方法可以在一秒钟之后立即淡出它。现在,它只是不断重复并添加到最后一个追加。我希望它在使用fadeOut后立即出现并消失。

更新:我是基于theIV和RaYell的回复做到的。它有效......但是它很优雅吗?

function saveCaption(id){

var queryString = $('#form'+id).formSerialize(); 

  $.ajax({

    type: "POST",

    url: "includes/ajax.php?request=saveCaption",

    data: queryString,

    success: function(response) {

        $('#form'+id).append('<div id="message">'+response+'</div>');

        setTimeout(function () {

          $('#message').fadeOut(function(){

            $(this).remove();

          });

        }, 1000);

    }

  });

  return false;

}

2 个答案:

答案 0 :(得分:4)

我想你会想要结合使用RaYell上面的回答但是在fadeOut回调中使用remove,否则它会继续附加到之前的追加 - 至少,我认为它会基于你表达你的问题的方式。这样的事情可以奏效:

setTimeout(function () {
  $('selector').fadeOut(function(){
    $(this).remove();
  });
}, 1000);

答案 1 :(得分:3)

在您附加消息后添加此内容(在成功回调内):

setTimeout(function () {
    $('selector').fadeOut();
}, 1000);

将选择器替换为与您的信息实际匹配的内容。