我想在使用jquery点击按钮后添加几个div



但每个div都包含标题,如:div-1、div-2、div-3。我点击div按钮的次数越多,标题就需要按顺序显示。提前谢谢。这是我的代码:

<div class="productDiv">
</div>
<div class="mt-3 text-center">
<button class="btn profile-button" style="color: white" type="button" 
id="btnAddtoList">Add Product</button>
</div>
$(function() {
var divCount = 0;
$('#btnAddtoList').click(function(){
divCount++;
var newDiv = $(
`<div class=item-wrapper-${divCount}>` +
'<div class="container rounded bg-white mt-3 mb-3">' +
'<div class="row">' +
'<div class="col-md-12">' +
'<div class="row mt-3">' +
'<span><strong>
Div Number #<span id="num"></span>
</strong></span>' +
'</div>' +
'<div class="row mt-1">' +
'<select class="product_option form-control" 
id="product" data-search="true">' +
'<option disabled selected>Select</option>'+
'</select>' +
'</div>' +
'<div class="row mt-3">' +
'<label class="labels" style="font-size: 16px">
Product Name
</label>
<input type="text" class="form-control" 
id="productName">' +
'</div>' +
'<div class="row mt-3">' +
'<label class="labels" style="font-size: 16px">
Sell Price
</label>
<input type="text" class="form-control" 
id="sellPrice">' +
'</div>' +
'<div class="row mt-3">' +
'<label class="labels">Amount</label>
<input type="number" class="form-control" 
id="amount">' +
'</div>' +
'<div class="mt-3 d-flex flex-column align-items- 
center 
text-center">
<button class="btn btn-danger deleteItem" 
type="button">Delete</button>
</div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>');
$('.productDiv').append(newDiv);
console.log(divCount);
document.getElementById("num").innerText = divCount;
});
});

我点击div按钮的次数越多,标题就需要按顺序显示。提前谢谢。

这应该是您想要的:

let counter = 0;
$('.button').on('click', function(){
counter++;
const div_title = 'div-'+counter;
$('.container').append('<div>'+ div_title +'</div>');
})
.container{
padding: 5px;
margin-top: 10px;
border: 1px dashed black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="button">Append DIV</button>
<div class="container"></div>

最新更新