首页 > 解决方案 > div 列表,插入位置的附加 div

问题描述

我有一个 div 列表,我希望在按下按钮时包含另一个 div。这个位置可以是随机的,即在开始、中间或底部。

我尝试了很多方法,但无法理解。如果有人可以提供帮助,将不胜感激。

我已经包括了一个小样本:

$(document).ready(function() {
  $("#btn2").click(function() {
    // This could be inserted at any point, i.e, start, middle or last;
    $(".bbc div").eq(2).prepend("<div>Appended item</div>");
  });

  $(".bbc div").click(function() {
    // On click return the eq() of the item;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="bbc">
  <div>List item 1</div>
  <div>List item 2</div>
  <div>List item 3</div>
  <div>List item 4</div>
</div>
<button id="btn2">Append list items</button>

标签: javascripthtmljquery

解决方案


您可以Math.random()用于在随机位置添加

  $("#btn2").click(function(){
    const divLength = $(".bbc div").length;
    const randomInteger = Math.floor(Math.random() * divLength) + 1
    $(".bbc div").eq(randomInteger).prepend("<div>Appended item</div>");
  });

更新的解决方案:https ://www.w3schools.com/code/tryit.asp?filename=GRAA36XMXJUH


推荐阅读