jQuery load()和.prepend() [英] JQuery load() and .prepend()

查看:62
本文介绍了jQuery load()和.prepend()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我有以下代码:

function() { 
$("ul#postbit").load('load.php').fadeIn("slow");
}, 3000);

我想要实现的是在加载load.php之后将结果放在<li>之前并使其淡入.此刻,它覆盖了ul#postbit中的内容.我只希望它加载新结果并保留其中的内容.我希望这是有道理的.

What I am trying to achieve is after loading load.php to prepend the results in to <li> and have it fade in. At the moment it overwrites what is in ul#postbit. I only want it to load new results and keep what was in there. I hope that makes sense.

推荐答案

.load()方法旨在以这种方式工作,即将Ajax响应直接加载到调用它的元素中.尝试使用其他 Ajax方法之一,例如:

The .load() method is designed to work that way, i.e., to load the Ajax response directly into the element(s) that you call it on. Try instead using one of the other Ajax methods, e.g.:

$.get("load.php", function(data) {
    $(data).prependTo("#postbit").fadeIn("slow");
});

这假设您的"load.php"返回包含li元素的html,当您说当前代码每次覆盖现有列表时,这似乎就是您要描述的内容.如果您的"load.php"仅返回不带<li>标记的新li的内容,则可以创建li并将其添加在前面:

This assumes your "load.php" returns html including li elements, which is what you seem to be describing when you say your current code overwrites the existing list each time. If your "load.php" returns just the contents for a new li without <li> tags then you can create the li and prepend it:

$.get("load.php", function(data) {
    $("<li/>").html(data).prependTo("#postbit").fadeIn("slow");
});

要使其不断重新加载,您可以将以上内容包装到用setInterval()调用的函数中,或执行类似的操作:

To have it continuously reload you could wrap the above into a function that you call with setInterval(), or do something like this:

function getMoreData() {
    $.get("load.php", function(data) {
        $(data).prependTo("#postbit").fadeIn("slow");
    }).complete(function() {
        setTimeout(getMoreData, 3000);
    });
}
getMoreData();

这使用setTimeout()安排3秒后再次运行getMoreData(),但是在上一个请求完成后才执行.

This uses setTimeout() to schedule another run of getMoreData() after 3 seconds, but it does so after the previous request completes.

这篇关于jQuery load()和.prepend()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆