使用.each

时间:2016-03-09 08:06:14

标签: jquery

var tr;
var data = [2003, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 1997, 1998, 1999, 2000, 2001, 2002, 1994, 1995, 1996, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1980, 1981, 1982, 1983, 1984, 1985, 1974, 1975, 1976, 1977, 1978, 1979];


$.each(data, function(index, value) {
  tr = $('<tr class="row" />');
  if () { //what condition to compare if current value is less than current to append lower value
    tr.append('<td>' + value + '</td>');
  }
  $('#table').append(tr);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='table'>
</table>

我想对表格进行排序。我无法获得当前值和之前的比较。

1 个答案:

答案 0 :(得分:1)

您已经有一个整数值数组,因此您可以在循环之前简单地在该数组上调用sort()来创建表。这里不需要复杂的订单检查逻辑。试试这个:

&#13;
&#13;
var tr = '';
var data = [2003, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 1997, 1998, 1999, 2000, 2001, 2002, 1994, 1995, 1996, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1980, 1981, 1982, 1983, 1984, 1985, 1974, 1975, 1976, 1977, 1978, 1979];

$.each(data.sort(), function(index, value) { // note the use of `sort() here
  tr += '<tr class="row"><td>' + value + '</td></tr>';
})
$('#table').append(tr);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='table'></table>
&#13;
&#13;
&#13;

如果您希望年份按降序排列,请使用data.sort().reverse()