追加对任意位置使用jQuery的内容? [英] Append content on random location with jQuery?

查看:173
本文介绍了追加对任意位置使用jQuery的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在一个页面来显示项目的列表,并且当前页是使用AJAX更新。每当一个新的项目推到我希望它出现在我的 UL列表

内随机位置客户端

下面是我在谈论的那种名单的一个例子:
http://jsfiddle.net/XEK4x/

HTML

 < UL类=ITEMLIST>
    <立GT;项目#2'; /李>
    <立GT;项目#2'; /李>
    <立GT;项目#3'; /李>
    <立GT;项目#4℃; /李>
< / UL>

CSS

  .itemlist李{
    宽度:100像素;
    高度:100像素;
    保证金:8像素;
    填充:4PX;
    浮动:左;
    背景:#DDDDDD;
}

任何想法如何,我在使用jQuery列表中的任意位置添加新的项目?
我知道我可以做类似 $(li_element).appendTo(ITEMLIST。); 但这将其追加到列表的底部

这可能是一个问题的另一件事情是,每个 li元素浮动到左边的事实。因此,当一个新的元素在中间加入,该元素后,一切都将被一个地方推到右边。

我可以用去几个无序列表向左浮动李的下彼此堆积,所以当新项目呈现列表只是得到的推下来,但如果我这样做随机的,有些无序列表可以得到比其他人长这样也看起来很奇怪。


解决方案

 变量$ LIS = $(李ITEMLIST);
$ lis.eq。后(Math.floor(的Math.random()* $ lis.length))(
                                            / *您在这里的新内容* /);

借助。经过()方法附加一个兄弟姐妹,所以从列表中选择一个随机元素<立GT; 项目并使用。经过()就可以了。或。之前()

P.S。对于新增加的项目推别人的权利,这是为什么有问题?是不是正常的,如果你有一个水平布局为您的列表?

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.

解决方案

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?

这篇关于追加对任意位置使用jQuery的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆