How to get the previous item with jquery each ()

I know that each function iterates through an array. Is there a way to access an index like (this is [i])? I need to compare the current pubDate with the previous pubDate, and if it differs by releasing a new pubdate.

$(data).find('item').each(function(i, value){ var title = $(this).find('title').text().replace(/\w+\s+\(.*?\)/, ""); var link = $(this).find('link').text(); var pubDate = $(this).find('pubDate').text(); alert(title); alert(link); alert(pubDate); $('#events').append("<p>" + title + "<br/>" + link + "</p>"); }); 
+4
source share
3 answers

One of many possible ways:

 var previous = null; $(data).find('item').each(function(i, value){ if (previous) { ... do stuff with previous element ... } var title = $(this).find('title').text().replace(/\w+\s+\(.*?\)/, ""); var link = $(this).find('link').text(); var pubDate = $(this).find('pubDate').text(); alert(title); alert(link); alert(pubDate); $('#events').append("<p>" + title + "<br/>" + link + "</p>"); previous = this; }); 

You need to check if the previous value is null, since the first iteration will contain a null value (the first element does not have the previous element).

+6
source

How about something like

 var previousDate = $(this).prev().find('pubDate'); 
0
source

you can use it and navigate

eg

 this.parent() 

gives an index

or

 i in your loop 
-1
source

Source: https://habr.com/ru/post/1332233/


All Articles