在div列表中的随机位置插入div

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

...
...
...
...

我想知道是否有一种方法可以在任何“item”div之间随机插入div,所以当页面加载时,它看起来像:

 
...
...
...
...
...

具有“item”类的所有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('
');

JS小提琴演示 。

略微改变,但更详细,替代上述:

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

JS小提琴演示 。

参考文献:

  • after()
  • eq()
  • insertAfter()
  • Math.floor()
  • Math.random()

尝试类似下面的内容,

 var $items = $('#container').find('.item'); var pos = Math.floor(Math.random() * $items.length) $('.randomDiv').insertAfter($items.eq(pos)); 

码:

HTML:

 

JS:

 $(document).ready(function(){ for(var i =1; i<10; i++) { $("#container").append("
Item
"); /*adding item divs dynamically */ } /*the real magic is below */ var rand_id = Math.floor((Math.random()*10)+1); /*generating an item divs ID randomly */ $("#"+rand_id).after("
Random DIv
"); /*adding the random div after that div of the rand_id */ });

小提琴: http : //jsfiddle.net/mareebsiddiqui/ULcTc/

说明:

这很简单。 首先,我通过分别从1开始并从10开始给它们ID来动态添加item div。然后我使用Math.floor()Math.random() JavaScript函数生成随机ID。 然后我用随机ID获取(使用一种简单的技术)div,然后在该div之后添加一个随机div。

如果你什么都没试,我不会提供代码。

但如果您不知道从哪里开始并需要工作流程:

减去容器中div的数量创建一个介于0和div数之间的随机数。

使用随机数索引在div后面附加div。

这将有效:

 function randomDiv() { var divCount = $(".item").length; var randomnumber=Math.floor(Math.random()*divCount); $("div.item:eq(" + randomnumber + ")").after("
hey im random
"); }

演示: http : //jsfiddle.net/meaFv/

根据代码行,这种情况下非jQuery答案等同于jQuery答案:

 // Assuming you already have a reference to the random div at "randomDiv" var container = document.getElementById('container'); var position = Math.floor(Math.random() * container.childNodes.length); container.insertBefore(randomDiv, childNodes[position]); 

这里的示例: http : //jsfiddle.net/qbqfR/按RUN一次以查看它的运行情况。

 var x=Math.floor(Math.random()*$('#container').children().length); $('#container div').eq(x).append('
YAY
');
 itemLength = $('#container .item').length; //quantity of .items randomPlace = Math.floor((Math.random()*itemLength)); //some random from 0 to .item length randomDiv = $('
',{ 'class':'randomDiv', text: randomPlace }); //.randomDiv $('#container .item').eq(randomPlace).after(randomDiv); //place it after the .item of position 'randomPlace'

http://jsfiddle.net/RaphaelDDL/4tpCy/

试试这个 –

 var $items = $('#container .item'); $items.eq(Math.floor(Math.random() * $items.length )) .after("
");