使用jQuery动态刷新有序列表 [英] Using jQuery to dynamically refresh an ordered list
问题描述
我有一个看起来如下的有序列表:
I have an ordered list that looks as follows:
<div class="col-md-2 panel panel-default">
<div class="panel-heading">Species Seen</div>
<div class="panel-body" style="height: 350px; overflow:auto">
<ol id="speciesAdded"></ol>
</div>
</div>
无序列表开始为空,用户可以在页面上向其中添加项目.或者,他/她可以单击按钮,并根据数据库中的条目创建列表.这是我遇到问题的部分(为列表充水).这是我的jQuery代码,它会进行AJAX调用并尝试刷新列表:
The unordered list starts out empty and the user can add items to it on the page. Or, he/she can click a button and have the list created from entries in a DB. This is the part (hydrating the list) I'm having a problem with. This is my jQuery code that makes an AJAX call and attempts to refresh the list:
$("#refreshButton").click(function () {
var url = "/FieldTrip/RefreshFieldTripSightingList";
var fieldTripName = $("#FieldTripName").val();
var accountRowId = $("#AccountRowId").val();
/* Clear any existing list */
$("ol#speciesAdded").empty();
$.getJSON(url, { accountRowId: accountRowId, fieldTripName: fieldTripName }, function (data) {
$.each(data, function (i, item) {
$("ol$speciesAdded").appendTo("li").text(item.species);
});
});
});
正在拨打AJAX,我拿回了物品.但是,我的排序列表在清除后不会用数据库中的项目刷新.
The AJAX call is being made and I get items back. But, my ordered list, after being cleared, does not refresh with items from the DB.
这是MVC 5应用程序.
This is an MVC 5 app.
推荐答案
$("ol$speciesAdded").appendTo("li").text(item.species);
选择器$
是错误的,我相信...
the selector $
is wrong, I believe...
// is what you wanted?
$("ol#speciesAdded").appendTo("li").text(item.species);
顺便说一句,如果您想让它刷新,我建议您先使用empty()
.
By the way, if you want to get it refreshed, i would suggest to use empty()
before.
$("ol#speciesAdded").empty();
另一个提示,如果使用appendTo
,则每次添加新项时都会让DOM重新呈现.表现不是很好.
One more tipp, if you use appendTo
you will let the DOM rerender every time a new item is added. that is not very performant.
尝试获取所有html,然后立即将其插入.
try to get all the html, and then insert it at once.
var items = [];
// in the loop then
items.push('<li>' + text + '</li>');
// insert all at once...
$("ol#speciesAdded").empty().html(items.join(""));
这篇关于使用jQuery动态刷新有序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!