我正在使用 jquery .load
函数从服务器加载结果并将其附加到我的 html 中:
$("#content").load('Get/classPosts?class=arts&min=1', function (responseText, textStatus, XMLHttpRequest) {
arr = $.parseJSON(responseText);
for (i = 1; i < arr.length; i++) {
if (arr[i] != null) {
$('#content').append("<section class='contentpost'><div class='contentimg'><a href='" + arr[i][0] + "'><img src='" + arr[i][2] + "'/></a> </div><div class='contenttitle title'><a href='" + arr[i][0] + "'>" + arr[i][1] + "</a></div></section>").slideDown(100);
}
}
});
就通过 .load
获取和显示数据而言,它很好,但我面临的问题很少:
- 最重要的是它实际上并没有将新数据附加到
#content
的末尾,但它只是替换现有的 html 与新的。 在
#content
顶部插入新数据之前,会显示原始 JSON 字符串,如下所示:[ ["93","Title-1","http://stackoverflow.com"], ["92"," Title-2","http://stackoverflow.com"], ["90"," Title-3","http://stackoverflow.com"], ["89"," Title-4","http://stackoverflow.com"], ["89"," Title-5","http://stackoverflow.com"], null,null,null,null,null]
我不知道为什么它会出现在页面上。
不过,这有点离题了,但如果有人也能帮我解决 .slideDown(100);
最后的功能,我会很高兴,我希望每个新内容都以动画向下滑动但它也不起作用。
谢谢!
最佳答案
load()
默认执行此操作。当您首先调用 load
时,您是在告诉它替换 #content
div 中的 html。您需要使用 GET
或 POST
来检索信息,然后将其附加到 #content
。
像这样:
$.get('Get/classPosts?class=arts&min=1', function (data) {
if(data.length > 0) {
arr = $.parseJSON(data);
var newId;
for (i = 1; i < arr.length; i++) {
if (arr[i] != null) {
// unique id for slidedown to work
newId = $('.contentpost').length;
$('#content').append("<section id='contentpost-"+newId+"' class='contentpost'><div class='contentimg'><a href='" + arr[i][0] + "'><img src='" + arr[i][2] + "'/></a> </div><div class='contenttitle title'><a href='" + arr[i][0] + "'>" + arr[i][1] + "</a></div></section>");
// slide down pointing to the newly added contentposts only
$('#contentpost-'+newId).slideDown(100);
}
}
}
});
您还需要做的是将 contentpost 类设置为隐藏在 css 中,例如:
.contentpost {
display:none;
}
您需要这个,否则滑动将不起作用。 div 需要隐藏。
关于javascript - append 不是附加内容而是替换它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17408624/