在div列表中的随机位置插入一个div [英] Insert a div in a random location in a list of divs
问题描述
我有一个看起来像这样的页面:
< 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>');
一个略有改变,但更详细的替代上述内容: 参考资料: I have a page that looks like so: 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: 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: A slightly altered, though more verbose, alternative to the above: References: 这篇关于在div列表中的随机位置插入一个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$('< div />',{
'class':'random',
'text':'...' $('。item')。eq(Math.floor(Math.random()* $('。item')。length)));
after()
。
eq()
。
insertAfter()
。
Math.floor()
。 Math.random()
。
<div id="container">
<div class="item">...</div>
<div class="item">...</div>
<div class="item">...</div>
<div class="item">...</div>
</div>
<div id="container">
<div class="item">...</div>
<div class="item">...</div>
<div class="rondomDiv">...</div>
<div class="item">...</div>
<div class="item">...</div>
</div>
$('.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>');
$('<div />', {
'class': 'random',
'text': '...'
}).insertAfter($('.item').eq(Math.floor(Math.random() * $('.item').length)));