我正在使用Jquery动态返回产品列表,将其呈现为HTML,然后使用$(selector).html(html)
在页面上显示..但是我注意到我是否过快地将产品添加到购物车(它调用再次渲染购物车的方法,有时会两次注入html。
例如,下面的代码是呈现菜单的内容:
html = " <table cellspacing=\"0\" width=\"270px\">\n";
html += " <tr>\n";
html += " <th>\n";
html += " <h1>\n";
html += " Current Order ID: " + $("input[name=cart_id]").val() + "\n";
html += " </h1>\n";
html += " </th>\n";
html += " </tr>\n";
html += " <tr id=\"cart_products\">\n";
html += " </tr>\n";
return $.ajax({
url: getAjaxUrl("cart/get_product"),
data: args,
type: 'get',
global : false,
success: function(data) {
if ( data.success ) {
//cart is empty
if ( data.data == "" ) {
html += " <td>\n";
html += " Your Cart is currently empty!\n\n";
html += " </td>\n";
} else if ( ("data" in data) ) {
html += " <td class=\"product\">\n\n";
html += " <table cellspacing=\"0\" width=\"100%\">\n\n";
html += " <tr>\n";
html += " <th>\n";
html += " Product\n\n";
html += " </th>\n";
html += " <th>\n";
html += " Qty\n\n";
html += " </th>\n";
html += " <th>\n";
html += " Action\n\n";
html += " </th>\n";
html += " </tr>\n";
//loop over all products in cart
$.each(data.data, function(i, product){
if ( i % 2 != 0 ) {
row_class = " alt";
} else {
row_class = "";
}
if ( ! product.ok ) {
row_class = " err";
}
//check if error
html += " <tr>\n";
html += " <td class=\"dsc" + row_class + "\">\n";
html += " <em>" + product.code + "</em><br />\n";
html += " " + product.description;
if ( product.whqc != "" )
html += " <br />WHQC: <strong>" + product.whqc + "</strong>\n";
else
html += " \n";
html += " </td>\n";
html += " <td class=\"qty + " + row_class + "\">\n";
html += " <input id=\"qty_" + product.id + "\" name=\"qty\" type=\"text\" value=\"" + product.qty + "\" class=\"qty\" maxlength=\"5\" size=\"5\" />\n";
html += " </td>\n";
html += " <td align=\"center\" class=\"action" + row_class + "\">\n";
html += " <img style=\"cursor:pointer; cursor:hand\" data-product_id=\"" + product.id + "\" id=\"cart_product_update\" src=\"" + getImageUrl() + "cart_product_update.png\" />\n";
html += " <img style=\"cursor:pointer; cursor:hand\" data-product_id=\"" + product.id + "\" id=\"cart_product_delete\" src=\"" + getImageUrl() + "cart_product_delete.png\" />\n";
html += " </td>\n";
html += " </tr>\n";
});
html += " </table>\n";
html += " </td>\n";
}
$("#cart_products").html(html);
} else {
alert("error");
}
}
});
从它所说的html += "<td class=\"product\">\n\n";
行开始有时会被推入html两次。
知道为什么会这样,以及如何阻止它?我认为使用html
方法是安全的,因为它不会附加 - 它会替换它,但似乎该方法正在踩踏自己的脚趾。我知道我可以使用像isLoading = true
这样的布尔值做一些事情,但是我想避免这样做。
答案 0 :(得分:0)
您可能应该正确初始化您的html变量:
var html = '';