如果在jquery中相同,请不要追加

时间:2012-03-02 05:40:36

标签: jquery

table1有内容(项目),而表2没有(因为它是购物车)现在我想做的是检查用户是否在购物车上添加相同的项目以及他/她是否这样做将添加数量,不写另一个tr。我怎么能这样做?

#table 1
<table>
  <tr><td>Item001</td><td>5.00</td></tr>
  <tr><td>Item002</td><td>5.00</td></tr>
</table>

#table 2 //it is blank because it will be filled later via onclick from table1
<table>
</table>

如果用户单击item001,它将被附加到table2,如果用户再次选择item001,它不能再在table2上写item001,而只会附加数量。

更新

var itemDesc = $(this).find('.desc').text();
var getPrice = $(this).find('.price').text();
var itemName = $(this).find('.itemName').text();
var currentId = $('#cartGrid tr').attr('id');

if(itemName == currentId)
{ 
    qty +=1;
    $('.tableQty').html(qty);
    qty = 1;
}
else{
    $('#cartGrid').append("<tr id="+ itemName +"><td>" + itemDesc + "</td><td class='tableQty'>"+ qty +"</td><td class='tablePrice'> $" + getPrice +"</td></tr>");

}

现在我开始工作了。但仅限于第一项。救命?谢谢你

2 个答案:

答案 0 :(得分:1)

我修改了你的代码以使其正常工作:

演示:http://jsfiddle.net/qmVHr/

// HTML

<table class="items">
  <tr>
    <td class="name">Item001</td><td>5.00</td>
  </tr>
  <tr>
    <td class="name">Item002</td><td>5.00</td>
  </tr>
</table>

<table class="shopping-cart"></table>​​​​​​​​​​​​​​​​​

// JS

$(function() {
  $('table.items td.name').click(function() {
    var itemName = $(this).text();
    var $addedItem = $('#' + itemName);

    if ($addedItem.length) {
      var qty = parseInt($addedItem.find('.qty').text());

      $addedItem.find('.qty').text(qty + 1);
    } else {
      $('<tr id="' + itemName + '"><td>' + itemName + '</td><td class="qty">1</td></tr>').appendTo($('table.shopping-cart'));
    }
});

您没有发布完整的代码,但似乎您的问题出在这一部分:

qty +=1;
$('.tableQty').html(qty); // this will update all the rows in your shoppingcart grid, not just the one you want
qty = 1; // not sure why you put 1 here, but this will always set the updated qty to be 1 + 1

答案 1 :(得分:-1)

我对jquery不太满意,但这可能会给你一个想法: http://jsfiddle.net/w39MV/2/

我正在为每个项目使用点击功能,当我们点击一​​个项目时,它会在.length的篮子中检查它的ID,如果存在则显示错误消息,否则将项目克隆到包含clone()和{{{ 1}}