$ .each jQuery查找项之间的常见值

时间:2016-10-03 22:55:58

标签: jquery each

给定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] = loc 1或loc 2等时,对项目进行分组的最佳方法是什么?

我需要向特定的地方或供应商发送采购订单,其中所有物品都来自公共地点(ation)

谢谢!

根据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组输出[]见图what I have now

我需要的是每个位置只有一次输入和发送PO:only have the inputs once per location (contents.loc)

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

正如我的评论所述:

  

您可以使用选择器中的data属性按特定数据属性对项目进行分组。示例:$(".send-po[data-loc=0]")将为您提供“send-po”类以及等于0的data-loc属性的所有项目

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

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

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

3)它允许您的数据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');
    });
});
相关问题