jquery每个循环显示已添加的项目 [英] Jquery each loop displays items already added
本文介绍了jquery每个循环显示已添加的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
函数refreshCart(){
console.log(in current cart)
var cartTable = $(。cart-table )
var cartBody = cartTable.find(。cart-body)
var productRows = cartBody.find(。cart-product)
var currentUrl = window.location.href
var refreshCartUrl ='/ api / cart /'
var refreshCartMethod =GET;
var data = {};
$ .ajax({
url:refreshCartUrl,
method:refreshCartMethod,
data:data,
success:function(data){
console.log(success)
console.log(data)
if(data.products.length> 1){
productRows.html()
$ .each(data.products,function(index,value){
cartBody.append(< tr>< th scope = \row \>+ index +< / th>< td colspan = 3>+ value +< / td>< / tr>)
})
}其他{
窗口。 (错误数据)
console.log(errorData) b
$ b})
}
解决方案
问题在于,当你第二次刷新购物车时,你的元素不会被清空。所以循环本身没有问题,你只需要先清空dom元素。像这样:
$(cartBody).empty()
只要在取出cartBody之后执行此操作,即可完成设置! :)
Can anybody advise why my Jquery loop (using each) displays all the past additions aswell? For instance, if I am adding item no 4 and items 1,2,3 are added it will display 1,2,3,1,2,3,4.... Any ideas?
function refreshCart(){
console.log("in current cart")
var cartTable = $(".cart-table")
var cartBody = cartTable.find(".cart-body")
var productRows = cartBody.find(".cart-product")
var currentUrl = window.location.href
var refreshCartUrl = '/api/cart/'
var refreshCartMethod = "GET";
var data = {};
$.ajax ({
url: refreshCartUrl,
method: refreshCartMethod,
data: data,
success: function(data) {
console.log("success")
console.log(data)
if (data.products.length > 1) {
productRows.html("")
$.each(data.products, function(index, value) {
cartBody.append("<tr><th scope=\"row\">" + index + "</th><td colspan=3>" + value + "</td></tr>")
})
} else {
window.location.href = currentUrl
}
},
error: function(errorData) {
console.log("error")
console.log(errorData)
}
})
}
解决方案
The problem is that you're dom element is not emptied when you refresh the cart a second time. So there's nothing wrong with the loop itself, you just have to empty the dom element before. Like this:
$(cartBody).empty()
Just do this after you've fetched the cartBody and you should be all set! :)
这篇关于jquery每个循环显示已添加的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文