最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to append div content in reverse order with jQuery - Stack Overflow

programmeradmin4浏览0评论

I have ajax call which gets results from database. But when I append div with html the order of content is reversed. How can I re-reverse it to set last item as a first. I don't want to order content in SQL. Is there a way to do this in jQuery?

$.each(data.idUser.matches, function(index, element) {
$('.myDiv').append('<div>...SOME LONG HTML CONTENT'</div')

I have ajax call which gets results from database. But when I append div with html the order of content is reversed. How can I re-reverse it to set last item as a first. I don't want to order content in SQL. Is there a way to do this in jQuery?

$.each(data.idUser.matches, function(index, element) {
$('.myDiv').append('<div>...SOME LONG HTML CONTENT'</div')
Share Improve this question edited Aug 31, 2017 at 15:19 Martin Thoma 137k172 gold badges674 silver badges1k bronze badges asked Feb 17, 2017 at 17:31 harunB10harunB10 5,20716 gold badges74 silver badges115 bronze badges 1
  • data.idUser.matches.reverse(),.... – Mihai Commented Feb 17, 2017 at 17:34
Add a ment  | 

3 Answers 3

Reset to default 11

You can use prepend instead of append to add at the top of a container rather than at the bottom of it.

Alternately, of course, just reverse the array before looping through it. Arrays have a built-in reverse method.

Or loop through it backward with a for loop.

You can use .prepend() here.

var data = [1, 2, 3, 4];

$.each(data, function(index, element) {
    $('.myDiv').prepend('<div>...SOME LONG HTML CONTENT - ' + index + '</div>');
});

Check out the fiddle to see it in action: https://jsfiddle/3xwmcnfu/

You can try using the Jquery.reverse() function, here's a fiddle with the example.

<ul class="ioi">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>

var i = 0;

$($("li").get().reverse()).each(function() {
  $( this ).html(i);
  i++;
});

https://jsfiddle/86LLftwe

发布评论

评论列表(0)

  1. 暂无评论