【发布时间】:2021-08-16 14:04:12
【问题描述】:
我正在构建一个表格,用于记录退伍军人的军事部署历史。该表单将默认为一个部署。它们最多可以加 3。我想要做的是,当您单击“添加部署”时,与 id="remaining" 关联的数字从 2 变为 1。如果您再次单击该按钮,则该按钮将被禁用并且 id ="remaining" 从 1 更改为 0。如果您单击删除按钮,则会发生相反的情况,因此如果您剩余 0 并且单击删除,它会更改为剩余 1 并且启用添加部署按钮。请参阅下面处理此 JS FIDDLE 的代码 注意 id="counter" 未使用,如果未使用,可以将其删除。
HTML
<div>
Location deployed:
<input type="text" size="15" placeholder="Location deployed"> Date deployed:
<input type="text" size="15" placeholder="Date deployed"> Date returned:
<input type="text" size="15" placeholder="Date returned">
</div>
<div id="counter">
<button class="add" type="button">Add Deployment</button>
<span id="remaining">2</span>
remaining
</div>
JQUERY
$('.add').click(function() {
$(this).before('<div>Location deployed: <input type="text" placeholder="Location
deployed" size="15" > Date deployed: <input type="text" placeholder="Date deployed"
size="15">
Date returned: <input type="text" placeholder="Date returned" size="15" > <span
class="remove"><button type="button"> Remove </button> </span></div>');
});
$(document).on('click','.remove',function() {
$(this).parent('div').remove();
});
【问题讨论】:
-
该按钮是通过脚本生成的,它不在 HTML 中。它最初不在代码中的原因是我不想让用户选择删除第一个 DIV。请参阅小提琴的链接,欢迎您为我更新它:)
-
对不起,我注意到不久之后,所以我从我的答案中删除了它。我的回答对你有意义吗?
-
要使用的重要 jquery 方法是 .attr()(启用/禁用按钮)和 .val()(获取 span 的内容)。您还可以使用 .prop() 修改启用/禁用属性,具体取决于您使用的 jquery 版本