$.each jQuery 找到项目之间的共同价值

$.each jQuery find common values between items

给定多个项目 class send-po 每个 data-loc=n

我有以下内容:

var qty = 0;
var loc = 0;
var product = '';
$('.send-po').each(function(i,item){
  qty = $(this).attr('data-qty');
  loc = $(this).attr('data-loc');
  product = $(this).attr('data-product');
});

当 loc[0] = loc1 or loc2 等时,对项目进行分组的最佳方法是什么?

我需要将采购订单发送到特定地点或供应商,所有物品都从一个公共地点发货

谢谢!

根据 mhodges 的建议,我做了以下事情:

for(var o=0;o<100;o++){
  $('.send-po[data-loc='+o+']').each(function(i,item){
    console.log(item);
    qty = $(this).attr('data-qty');
    loc = $(this).attr('data-loc');
    product = $(this).attr('data-product');
  });
}

我想我可以用这个。谢谢 mhodges!

另一个相关问题:

var orders = '<table>';
$.each(cart,function(j,contents){
  if(contents[n].loc === contents[o].loc){
    //group the two 
  } else {
    orders += '<tr><td>'+contents.qty+'<br/>Sending from '+contents.loc+'</td><td>'+contents.product+'<br>'+contents.options+'<br>'+comments+'</td><td>'+number_format(order.Price,2,'.',',')+'</td><td>'+number_format(order.subtotal,2,'.',',')+'</td></tr>';
    orders += '<tr><td><input class="carrier" id="carrier_'+contents.cartId+'" placeholder="Carrier"></td><td><input class="tracking" id="cartid_'+contents.cartId+'" data-item="'+contents.product+' '+contents.options+'" placeholder="Tracking # for this item"><button class="btn-small send" id="send-tracking_'+contents.cartId+'">Send</button></td><td><input type="hidden" class="send-po" data-loc="'+contents.loc+'" data-product="'+contents.product+' '+contents.options+'" data-qty="'+contents.qty+'"><textarea id="afs-comments-'+contents.loc+'" placeholder="Comments to Vendor"></textarea><br/><button id="sendPO-'+contents.loc+'">Send PO</button></td></tr>';
    orders += '<tr><td colspan="4"><hr></td></tr>';
  }
});
orders += '</table>';
$('#orders').html(orders).show();

现在每个内容我有 2 组输出[] 见图 )

我需要的是在每个位置只发送一次输入和发送采购订单:

有什么建议吗?

如我的评论所述:

You can use the data attribute in a selector to group items by a certain data attribute. Example: $(".send-po[data-loc=0]") will get you all of the items with the class "send-po" as well as a data-loc attribute equal to 0

如果您不知道要查找哪个值,或者您希望遍历所有可能的值,而不是猜测您有多少个值并使用一组静态值创建 for 循环,您实际上可以随时检索当前值列表,然后迭代这些值。这在三个方面对您有帮助:

1) 它删除了任何不必要的循环迭代/操作

2) 它使您的代码可扩展且面向未来

3) 它允许您的 data-loc 值是任何值 - 字符串、非序列号等。

代码可能如下所示:

// Get the current list of all data-loc values
var locations = [];
$(".send-po[data-loc]").each(function () {
    var location = $(this).data("loc");
    // check to see if the value is already in the array
    if (locations.indexOf(location) === -1) {
        // if not, push it onto the array
        locations.push(location );
    }
});
locations.each(function (index, location) {
    // group the .send-po by data-loc value
    $('.send-po[data-loc='+ location + ']').each(function(i,item){
        console.log(item);
        qty = $(this).attr('data-qty');
        loc = $(this).attr('data-loc');
        product = $(this).attr('data-product');
    });
});