我正在建立一个想要捕捉退伍军人军事部署历史的表格。表单将默认为一个部署。它们最多可以加3个。我想要做的是当你点击“添加部署”时,与id =“remaining”相关联的数字从2变为1.如果再次单击该按钮,该按钮将被禁用并且id =“剩余”从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();
});
答案 0 :(得分:1)
尝试检查范围的值并在.click()中验证,如:
$('.add').click(function () {
var $remind = parseInt($('#remaining').text());
if($remind != 0){
$(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>');
$remind = $remind - 1
$('#remaining').text($remind);
}
else{
console.log('All added');
$('.add').prop('disabled', true);
}
});
$(document).on('click', '.remove', function () {
$(this).parent('div').remove();
var $remind = parseInt($('#remaining').text());
$remind = $remind + 1
$('#remaining').text($remind);
if$('.add').prop('disabled', false);
});
答案 1 :(得分:1)
我不确定你会遇到什么问题,但是应该这样做:
http://jsfiddle.net/mmilleruva/9C6Lw/
var remaining = 2;
function UpdateRemaining(isAdd){
if(isAdd){
remaining = remaining - 1;
}
else{
remaining = remaining + 1;
}
$('#remaining').text(remaining);
if(remaining == 0){
$('#btn').prop("disabled",true);
} else{
$('#btn').prop("disabled",false);
}
}
$('.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>');
UpdateRemaining(true);
});
$(document).on('click', '.remove', function () {
$(this).parent('div').remove();
UpdateRemaining(false);
});
答案 2 :(得分:0)
您需要跟踪部署情况,这似乎是您在跨度中所做的事情。您可以通过选择$("#remaining").val()
然后递增并根据用户点击减少它来获取此信息。
在删除功能中,增加范围,在添加功能中减少所述范围。在你的add函数中,你有一个if条件,看看#remaining span的val是否为0,如果是,你禁用添加按钮$('。add).attr('enabled',false)或类似的东西。在你的删除函数中,你做同样的事情,除了检查它是否已经增加到1,然后将enabled设置为true。