问题描述:

Having a script loading some content from my database (PHP).

i echo it like this:

<ul class="list-unstyled">

<li><a class="<?php echo $newDate; ?>" href="#" data-toggle="modal" data-target="#<?php echo $row[id]; ?>"><?php echo "$row[ordreid] - $row[navn] - $row[valg] - $row[dato]"; ?></a></li>

</ul>

Now i wanna group it by year - so it with jquery finds all class with 2015 and appends some text before the first one and does the same with 2016 2017 ... but only if there is some data with that year.

My idea was to make a loop for each finded year and append some text before the first one, and came up with this:

for (i = 2014; i < 2060; i++) {

var n = i+1;

if($("a[class*='"+i+"']").last().closest( "li" ).before().append( "<hr><h3>"+n+"</h3>" ));

}

This one doesnt append something before my 2015 year, and it still add 2017 even thoug i dont have any :/

Someone that can help?

网友答案:

With the code you have shown, I can suggest you to try the following-

for (i = 2014; i < 2060; i++) { 
  var $year = $("a[class*='"+i+"']");
  if ($year.length) {
    var n = i+1;
    $year.first().closest( "li" ).prepend( "<hr><h3>"+ n +"</h3>" );
  }
}
相关阅读:
Top