jQuery迭代逻辑问题。函数中的逻辑

时间:2012-08-22 16:05:33

标签: jquery

JQuery noob在这里。我需要一些帮助,这是基本的,但如果有人能帮助我,我真的很感激。我正在制作一个旧的怪诞页面,需要比较出发/到达的日期,看看它们是否无效。这是我想出的比较完美工作日期(一个日期)的逻辑。

我遇到的问题是需要比较9个日期,#AD1和#DD1到#AD9和#DD9,每行在一个单独的表行中,其中一个类名为“.dateVal”。如何封装此代码以在函数中运行这9个日期?我非常感谢提前帮助..非常感谢!

  var strErrors = '';
  var strRequired = '';

  var iniString = '';
  var endString = '';
  var dateIni = $('#AD1').val().split('/');
  var dateEnd = $('#DD1').val().split('/');
  $.each(dateIni, function (index, value) {
   iniString = iniString + value;
  })
  $.each(dateEnd, function (index, value) {
   endString = endString + value;
  })

  iniString = parseInt(iniString, 10);
  endString = parseInt(endString, 10);


  if (iniString > endString) {
   strErrors = strErrors + ' - Departure/Arrival dates are incorrect.  \n'
  }

2 个答案:

答案 0 :(得分:0)

一种方法是在jQuery选择器中使用连接和一个简单的JavaScript for循环:

var strErrors = '';

var iniString = '';
var endString = '';

for (var ii = 1; ii <= 9; ii++) {
    var dateIni = $('#AD' + ii).val().split('/');
    var dateEnd = $('#DD' + ii).val().split('/');

    $.each(dateIni, function (index, value) {
        iniString = iniString + value;
    });

    $.each(dateEnd, function (index, value) {
        endString = endString + value;
    });

    iniString = parseInt(iniString, 10);
    endString = parseInt(endString, 10);   

    if (iniString > endString) {
        strErrors = strErrors + ' - Departure/Arrival dates are incorrect.  \n'
    }
}

现在,如果您想将该逻辑封装到几个函数中:

var strErrors = '';

function checkAllDates() {
    for (var ii = 1; ii <= 9; ii++) {
        checkDate(ii);
    }
}

function checkDate(ii) {
    var iniString = '';
    var endString = '';

    var dateIni = $('#AD' + ii).val().split('/');
    var dateEnd = $('#DD' + ii).val().split('/');

    $.each(dateIni, function (index, value) {
        iniString = iniString + value;
    });

    $.each(dateEnd, function (index, value) {
        endString = endString + value;
    });

    iniString = parseInt(iniString, 10);
    endString = parseInt(endString, 10);   

    if (iniString > endString) {
        strErrors = strErrors + ' - Departure/Arrival dates are incorrect.  \n'
    }
}

答案 1 :(得分:0)

您可以使用$.each代替replace来避免使用split来删除/个字符。

var strErrors = '',
    iniNum,
    endNum,
    dateIni,
    dateEnd,
    numDates = $('.dateVal').length / 2; // assumes matching pairs of dates

// assuming your date values are always yyyy/mm/dd format?
for (var i = 1; i <= numDates; i++) {
    dateIni = $('#AD' + i).val().replace('/','');
    dateEnd = $('#DD' + i).val().replace('/','');

    iniNum = parseInt(iniString, 10);
    endNum = parseInt(endString, 10);   

    if (iniNum > endNum) {
        strErrors += ' - Departure/Arrival dates are incorrect.  \n';
    }
}