使用 JavaScript 动态添加 div



我希望用户应该能够在单击加号图标时动态添加 5 个div,之后警报应该只可以添加 5 个div,但奇数不会到来。

function addvv() {
var numItems = $('div.box').length;
if (numItems <= 5) {
$('.box').clone().appendTo('.container');
var x = document.getElementById("removediv");
if (x.style.display === "none") {
x.style.display = "block";
}
} else {
alert('only 5 can be added');
}
}
function removediv() {
$(".box").remove();
}
<div class="container">
<div class="box">
<div style="background-color:blue;height: 26px;border-radius: 14px;">
//this is the button to add divs dynamically
<i class="fas fa-plus" id="adddiv" onclick="addvv()" style="color: red;float: right;margin-right: 15px;margin-top: 2px;font-size: 18px;"></i>
<i class="fa fa-trash" id="removediv" onclick="removediv()" style="color: red;float: right;margin-right: 15px;margin-top: 2px;font-size: 18px;display:none"></i>
</div>
<div class="row" style="background-color:lightgray;height:100px;border-radius: 23px;">
<div class="col-md-12" style="padding:10px">
<div class="col-md-6">
<label>Name:</label>
<input type="text" id="name" />
</div>
<div class="col-md-6">
<label>Salary:</label>
<input type="text" id="salary" />
</div>
</div>
</div>
</div>
</div>

请建议一些功能,以便我也可以添加奇数个div。谢谢

您的代码存在几个问题。首先,您的条件numLength <= 5允许在numLength == 5时运行clone(),总共允许 6 个克隆,而不是您想要的 5 个。其次,$('.box').clone()将克隆与选择器.box匹配的所有元素。这意味着第一次单击时它将克隆一个,第二次单击它将克隆两个,依此类推。

我已经修复了您的代码,以便它只克隆一个,在除第一个.box之外的所有代码上显示#removediv,并删除单击#removediv.box。此外,ids对于整个文档应该是唯一的,所以实际上你应该使用类。

function addvv() {
var numItems = document.getElementsByClassName('box');
if (numItems.length < 5) {
$('.box').first().clone().appendTo('.container');
$('.box').not(':first').find('#removediv').css('display', 'block');
}
else {
alert('only 5 can be added');
}
}
function removediv(e) {
$(e).closest('.box').remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="box">
<div  style="background-color:blue;height: 26px;border-radius: 14px;">
<!-- //this is the button to add divs dynamically -->
<i class="fas fa-plus" id="adddiv" onclick="addvv()" style="color: red;float: right;margin-right: 15px;margin-top: 2px;font-size: 18px;">+</i>
<i class="fa fa-trash" id="removediv" onclick="removediv(this)" style="color: red;float: right;margin-right: 15px;margin-top: 2px;font-size: 18px;display:none">-</i>
</div>
<div class="row" style="background-color:lightgray;height:100px;border-radius: 23px;">
<div class="col-md-12" style="padding:10px">
<div class="col-md-6">
<label>Name:</label>
<input type="text" id="name" />
</div>
<div class="col-md-6">
<label>Salary:</label>
<input type="text" id="salary" />
</div>
</div>
</div>
</div>
</div>

最新更新