javascript - 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>
解决方案
您可以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
推荐阅读
- c++ - 关于 C++ 中数据结构的迭代器和指针的问题
- jquery - 如何使用 jquery 切换到下一个父行?
- curve-fitting - 通过线性方程 y = mx 的原点进行曲线拟合
- python - 仅在开始日期和结束日期之间按标识符对两列求和
- fortran - Fortran Preprocessor Macro with Newline
- mysql - 从上午 10 点到下午 4 点获取记录
- c# - 如何为用 C 编写的 scrcpy 扩展 .Net 包装器的功能?
- mysql - 需要将 2 个查询合并为 1 个
- paraview - 获取在 renderView 上单击的点的坐标
- c# - Visual Studio Tools for Office Edit multiple files