开发者

how to get previous element with jquery each()

开发者 https://www.devze.com 2023-01-31 06:16 出处:网络
I know the each function iterates over an array. Is there way to access the indice like (this[i])? I need to be able compare current element\'s pubDate with the previous element\'s pubDate and if it\'

I know the each function iterates over an array. Is there way to access the indice like (this[i])? I need to be able compare current element's pubDate with the previous element's pubDate and if it's different output 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>");

        });


One of many potential ways would be:

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 have to check to see if previous is not null, since the first iteration will contain a null value (the first element doesn't have any previous element).


How about something like

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


you can use this and traverse

for example

this.parent() 

gives you the index

or

i in your loop
0

精彩评论

暂无评论...
验证码 换一张
取 消