我有以下 html 代码
<ul class="sales_details clearfix">
<li class="blue_disc">
<a id="product_detail" href="">Som stuff</a>
<span id="product_revenue">$45</span>
</li>
</ul>
<input class="update" type="button">
我的jquery
代码是
$(document).ready(function () {
$('.update').click(function() {
var array_list = response_list; // I will get response_list from somewhere as list of dictionaries
$.each(array_list, function (i, item) {
href = "/products/" + item.products__id + "/"
$('#product_detail').attr('href', href).html(item.products__name);
$('#product_revenue').html(item.revenue);
});
});
});
因此,当从我上面的 html 和 jquery 代码中时,带有 blue_disc
类的 li 元素
正在更新,但这些值是重写的,因此我可以看到只有一条记录为 li
例如,我的 array_list
如下:
[{'products__name':'One', 'revenue':'45'},
{'products__name':'two', 'revenue':'32'},
{'products__name':'three', 'revenue':'35'}]
我只能看到一个带有 product__name : Three
数据的 li
元素,
所以我想做的是
- 首先删除
blue_disc
类的li 元素
(因为默认情况下我会显示一些数据) - 创建一个 li 元素,如上面的详细信息所示,
那么如何
- 删除带有类的
li 元素
- 如何使用上面的
sales_details
类更新ul
之后的元素?
最佳答案
首先,您的click
语法是错误的。其次,您要更新现有元素的属性,而不是在循环中创建任何新元素。试试这个:
$('.update').click(function () {
$('.sales_details').empty();
var array_list = response_list;
$.each(array_list, function (i, item) {
var $li = $('<li />').appendTo('.sales_details');
$('<a />', {
'href': "/products/" + item.products__id + "/",
'text': item.products__name
}).appendTo($li);
$('<span />', {
'text': '$' + item.revenue
}).appendTo($li);
});
});
关于jquery - 如何使用 jquery 在 ul 标签内删除和添加 li 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19809714/