我有两个功能'添加'和'删除'。我有一个限制,添加15个输入文本字段,我有一个计数器。现在我必须删除字段以减少计数器值。我已经为每个输入字段动态添加了删除按钮。但是我无法正确删除输入字段。
$(document).ready(function() {
var counter = 2;
$(function() {
$("#new_addButton,#addButton").bind("click", Add);
});
function Add() {
if (counter > 15) {
$('.not_more_than_fifteen').show();
alert(counter);
return false;
}
var newTextBoxDiv = $(document.createElement('li')).attr("id", 'job_responsibility' + counter);
newTextBoxDiv.after().html('<input type="text" class="new_highlight high_light" placeholder="Enter job responsibility" name="textbox' + counter + '" id="textbox' + counter + '" value="" ><span class="remove_me"><i class="fa fa-trash"></i></span>');
newTextBoxDiv.appendTo(".new_highlight");
counter++;
$(".remove_me").on("click", Delete);
}
function Delete() {
alert(counter);
$(this).parent().remove();
counter = counter - 1;
console.log(counter)
return false;
}
});
<ul class="new_highlight">
<li><input class="form-control high_light" placeholder="" value="Driven and motivated individual who thrives in a dynamic and evolving environment." type="text"></li>
<li><input class="form-control high_light" placeholder="" value="Basic understanding of TCP/IP and Internet-facing firewalls." type="text"><span class="remove_me"><i class="fa fa-trash"></i></span></li>
<li><input class="form-control high_light" placeholder="" value="Minimum of five years of Linux and Windows administration" type="text"><span class="remove_me"><i class="fa fa-trash"></i></span></li>
<li><input class="form-control high_light" placeholder="" value="Experience in configuration and troubleshooting of Tomcat server engine" type="text"><span class="remove_me"><i class="fa fa-trash"></i></span></li>
</ul>
<div class="">
<span class="pull-left btn-add" id="addButton">Add More Responsibilities</span>
<span class="not_more_than_fifteen pull-right">You have already added 15 rows!</span>
<div class="clear"></div>
</div>
答案 0 :(得分:0)
您的代码有点令人困惑,并且其中包含不必要的代码。我的解决方法是这个;
HTML
<button id="add">add</button>
JS
var counter=0;
$(document).ready(function(){
$('#add').click(function(){
if(counter<15){
var inp = document.createElement('input');
var del = document.createElement('button');
$(del).addClass('delete');
$(del).attr('onclick','remove(this)');
$(del).text('delete');
$('#add').after(inp);
$('#add').after(del);
$('#add').after('<br>');
counter++;
}
});
});
function remove(e){
$(e).next('input').remove();
$(e).prev('br').remove();
$(e).remove();
counter--;
}