Jquery 更新a<;ul>;并使用第一个<;李>;作为具有克隆功能的模板
为了更新结果列表,我从Ajax接收到一个JSON字符串。 如果是“查看更多”,我会添加列表。如果是新的搜索,我会先清除列表。 A一旦ajax调用被触发,加载Jquery 更新a<;ul>;并使用第一个<;李>;作为具有克隆功能的模板,jquery,ajax,list,clone,Jquery,Ajax,List,Clone,为了更新结果列表,我从Ajax接收到一个JSON字符串。 如果是“查看更多”,我会添加列表。如果是新的搜索,我会先清除列表。 A一旦ajax调用被触发,加载就会添加到列表的底部。 下面公开的已简化。我不想单独添加每个和其他元素,而是使用第一个作为后续结果的模板 这是简化的HTML代码 <ul id="list"> <li> <span class="itemPriceSell">1234</span> <span class="i
就会添加到列表的底部。
下面公开的
已简化。我不想单独添加每个
和其他元素,而是使用第一个
作为后续结果的模板
这是简化的HTML代码
<ul id="list">
<li>
<span class="itemPriceSell">1234</span>
<span class="itemPriceRent">56</span>
</li>
<li>
<span class="itemPriceSell">9876</span>
<span class="itemPriceRent">54</span>
</li>
</ul>
问题
它只在
的底部添加了一个带有最后一个JSON值的
,但我没有添加来自JSON的10个结果。console.log始终输出相同的结果(内部最后一个JSON结果作为售价和租金)
任何关于我的错误的帮助都将不胜感激。
谢谢。您需要为每个要插入的项目克隆一次模板,而不是在循环开始前克隆一次 试着这样做:
function refreshResults(data) {
filtersChanged() ? $('ul#list li:not(:last)').remove() : null
var template = $('ul#list li:first');
$.each(data, function(index, hbid) {
var cloned = template.clone();
cloned.find('.itemPriceSell').text(hbid.sellprice);
cloned.find('.itemPriceRent').text(hbid.rentprice);
cloned.insertBefore('ul#list li:last');
console.log(cloned);
});
$('ul#list li:last').remove();
}
通过只克隆一次,您的原始代码将获取单个克隆项,并对其重复执行以下操作:
哇,又快又准。非常感谢。
function refreshResults(data) {
filtersChanged() ? $('ul#list li:not(:last)').remove() : null
var template = $('ul#list li:first');
$.each(data, function(index, hbid) {
var cloned = template.clone();
cloned.find('.itemPriceSell').text(hbid.sellprice);
cloned.find('.itemPriceRent').text(hbid.rentprice);
cloned.insertBefore('ul#list li:last');
console.log(cloned);
});
$('ul#list li:last').remove();
}