1

JQuery 菜鸟在这里。我需要一些基本的帮助,但如果有人能帮助我,我将不胜感激。我正在处理一个旧的怪诞页面,该页面需要比较出发/到达日期以查看它们是否无效。这是我想出的比较完美的日期(一个日期)的逻辑。

我遇到的问题是有 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'
  }
4

2 回答 2

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'
    }
}
于 2012-08-22T16:11:37.767 回答
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';
    }
}
于 2012-08-22T16:25:40.090 回答