jquery - 我想在使用 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>
推荐阅读
- php - 如何检查 html/php 中的按钮是否被按下
- ruby-on-rails - 用于复杂类型数组的 Ruby on Rail 位运算符 (&)
- sql - 使用 SELECT 方法向 SQL 查询中的列添加数字值
- c# - 使用 USB 名称获取 USB 的序列号
- amazon-iam - AWS 假定角色无法在无服务器项目中执行 secretsmanager:GetSecretValue
- android - 我不能在我的模拟器上运行这个应用程序有人能帮我吗
- python - 在不同的会话中加载 TensorFlow 模型会产生不正确的结果
- javascript - 如果加载失败,如何重置 p5.js 草图
- python - 如果命令是函数的名称,如何运行函数?
- python - 使用数据透视表 pd 更改 python pandas 中的列顺序