Append content on random location with jQuery?

拈花ヽ惹草 提交于 2019-12-10 15:55:00

问题


I need to display a list of items in a page, and this page is updated with AJAX. Every time a new item is pushed to the client I want it to appear at a random location inside my ul list.

Here's an example of the kind of list I'm talking about: http://jsfiddle.net/XEK4x/

HTML

<ul class="itemlist">
    <li>Item #2</li>
    <li>Item #2</li>
    <li>Item #3</li>
    <li>Item #4</li>
</ul>

CSS

.itemlist li{
    width:100px;
    height: 100px;
    margin: 8px;
    padding: 4px;
    float: left;
    background: #dddddd;
}

Any ideas how I add new items at a random location in the list using jquery? I know I can do something like $(li_element).appendTo(".itemlist"); but this will append it to the bottom of the list.

Another thing that might be a problem is the fact that each li element is floated to the left. So when a new element is added in the middle, everything after that element will be pushed one spot to the right.

I could go with several ul lists floated left, and the li's stacked under each other, so when a new item is rendered the list simply get's pushed down, but if I do this at random, some ul lists could get longer than others which would also look strange.


回答1:


var $lis = $(".itemlist li");
$lis.eq(Math.floor(Math.random()*$lis.length)).after(
                                            /* your new content here */ );

The .after() method appends a sibling, so select a random element from the list of <li> items and use .after() on it. Or .before().

P.S. Regarding a newly added item pushing the others to the right, why is that a problem? Isn't that normal if you have a horizontal layout for your list?




回答2:


Try something like this:

var randomNum = Math.floor(Math.random()*9);
$(".itemlist li").eq(randomNum).append("HI");

Just create a random number in javascript. Then select that random element in the list and append the new content. Unless I am not understanding the question.




回答3:


with accepted answer a new element never gets inserted as first. the position where it can be inserted is number of elements plus one. between elements + beginning + end.

the code is not really nice but fixes it.

http://jsfiddle.net/XEK4x/38/

var $lis = $(".itemlist li");
var pos = Math.floor(Math.random() * ($lis.length + 1)) - 1;
if(pos != -1){
  $lis.eq(pos).after("<li>new</li>");
} else{
  $lis.eq(0).before("<li>new first</li>");
}


来源:https://stackoverflow.com/questions/8002627/append-content-on-random-location-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!