在div列表中的随机位置插入一个div [英] Insert a div in a random location in a list of divs

查看:142
本文介绍了在div列表中的随机位置插入一个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的页面:

 < div id =container> 
< div class =item> ...< / div>
< div class =item> ...< / div>
< div class =item> ...< / div>
< div class =item> ...< / div>
< / div>

我想知道是否有方法可以随意插入div 之间的任何项目divs,所以当页面加载时,它会像这样:

 < div id = 容器 > 
< div class =item> ...< / div>
< div class =item> ...< / div>
< div class =rondomDiv> ...< / div>
< div class =item> ...< / div>
< div class =item> ...< / div>
< / div>

所有带有item类的div都是动态生成的,不能修改。有任何想法吗?
在此先感谢!

解决方案

我建议,等待进一步的信息:

  $('。item')。eq(
/ *我使用eq()方法来选择特定元素
和在方法内创建随机数(范围从0-(元素数))
以避免创建不必要的变量* /
Math.floor(Math.random()* $('。item')。length)
/ * after()从html字符串中创建一个元素,并将其插入到
之后的eq()方法* /
).after('< div class =random>< / div>');



一个略有改变,但更详细的替代上述内容:

  $('< div />',{
'class':'random',
'text':'...' $('。item')。eq(Math.floor(Math.random()* $('。item')。length)));

JS Fiddle演示



参考资料:


I have a page that looks like so:

<div id="container">
  <div class="item">...</div>
  <div class="item">...</div>
  <div class="item">...</div>
  <div class="item">...</div>
</div>

I was wondering if there is a way that I could insert a div randomly between any of the "item" divs, so when the page is loaded, it would look like:

<div id="container">
  <div class="item">...</div>
  <div class="item">...</div>
  <div class="rondomDiv">...</div>
  <div class="item">...</div>
  <div class="item">...</div>
</div>

All the divs with the "item" class are dynamically generated, and cannot be modified. Any ideas? Thanks in advance!

解决方案

I'd suggest, pending further information:

$('.item').eq(
    /* I'm using the eq() method to select a specific element,
       and creating the random number (in the range from 0-(number-of-elements))
       within the method to avoid creating unnecessary variables. */
    Math.floor(Math.random() * $('.item').length)
    /* after() creates an element from the html string, and inserts it after
       the element selected earlier with the eq() method */
).after('<div class="random"></div>');

JS Fiddle demo.

A slightly altered, though more verbose, alternative to the above:

$('<div />', {
    'class': 'random',
        'text': '...'
}).insertAfter($('.item').eq(Math.floor(Math.random() * $('.item').length)));

JS Fiddle demo.

References:

这篇关于在div列表中的随机位置插入一个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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