开发者

reuse jquery html selectors loop

I am looking for best practice to use jquery loop.

I have a jquery loop, like this:

$.each(rows, function(){
  var rowClass = $.trim(this);
  $('table.' + o.MainTableClass).append('<tr class="'+rowClass+'" />');
  $('.'+rowClass).find('.ItemRow').each(function(){
    var date = $(this).find('span.Date').text().split(o.dateSpliter).pop();
    if($.inArray(date,usedYears)==-1)
    {
      usedYears.push(date);
    }
  });
});

The idea is, that i have to reuse this loop again except this part:

if($.inArray(date,usedYears)==-1)
{
  usedYears.push(date);
}

I mean pretty m开发者_如何学JAVAuch everything what is in second loop. I can just "copy/paste" an use the same loop again, but I am feeling that it is not the best practice to go this way.

Maybe I can cash this loop, or drop into some function, what do you suggest me to use in this case ?

Thanks


Use a function instead, send date and usedYears and get both as return params.


Define a higher-order function:

function eachRow(func) {
  $.each(rows, function() {
    var rowClass = $.trim(this);
    $('table.' + o.MainTableClass).append('<tr class="' + rowClass + '" />');
    $('.' + rowClass).find('.ItemRow').each(function() {
      var date = $(this).find('span.Date').text().split(o.dateSpliter).pop();
      func(date);
  });
});

Then:

var usedYears = [];
eachRow(function (date) {
  if($.inArray(date,usedYears)==-1)
  {
      usedYears.push(date);
  }
});

To re-use:

eachRow( function (date) {
  //do stuff with date.
});

You can pass more stuff into func if you need to use it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜