任何人都可以告诉我 如何在每行上添加删除按钮 从下面的代码 [的jsfiddle] [1]
var counter = 1;
jQuery('a.add-author').click(function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<div class="row"><div class="col-lg-6"><input type="text" name="first_name' +
counter + '"/></div><div class="row"><div class="col-lg-6"><input type="text" name="last_name' +
counter + '"/></div></div>');
jQuery('div.row').append(newRow);
});
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-lg-6"><input type="text" name="first_name" /></div><div class="col-lg-6"><input type="text" name="last_name" /></div>
</div>
<a href="#" title="" class="add-author">Add Author</a>
答案 0 :(得分:2)
要“删除”元素,您可以使用jQuery('element').remove()
函数。
通过使用jQuery('element').on()
,即使稍后创建了元素,您也可以收听事件。
请仔细阅读有关.on()
的文档!
var counter = 1;
jQuery('a.add-author').click(function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<div class="row"><div class="col-lg-6"><input type="text" name="first_name' +
counter + '"/></div><div class="col-lg-6"><input type="text" name="last_name' +
counter + '"/></div><div><a href="#" class="delete">delete</a></div></div>');
jQuery('.add-author').before(newRow);
});
//Bound to 'body' for this sample, bind to you own wrapper element when using this!
jQuery('body').on('click', '.delete', function(event)
{
event.preventDefault();
$(this).closest('.row').remove();
});
.row { position: relative; width: 500px; height: auto; margin: 5px 0; overflow: hidden; }
.row div { position: relative; float: left; width: 150px; height: auto; overflow: hidden; }
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-lg-6"><input type="text" name="first_name" /></div><div class="col-lg-6"><input type="text" name="last_name" /></div>
</div>
<a href="#" title="" class="add-author">Add Author</a>