2015-06-24 54 views
1

我有一个HTML如下:jQuery的:按钮添加和最接近删除

<div class="parent-wrapper"> 
    <div class="test-guided-search-row"> 
     <select class="form-control test-guided-search-row-select-bool-query"> 
      <option>AND</option> 
     </select> 

     <select class="form-control test-guided-search-row-select-query-path"> 
      <option>ALL</option> 
     </select> 

     <select class="form-control test-guided-search-row-query-type"> 
      <option>abcd</option> 
      <option>efg</option> 
     </select> 

     <input class="form-control" type="text"> 

     <button class="btn btn-primary btn-sm" type="button" data-button-action="addRow">+</button> 
     <button class="btn btn-primary btn-sm" type="button" data-button-action="deleteRow">-</button> 
    </div> 
</div> 

我怎样才能让这个按钮+接下来将增加整个行div到div中的按钮,这是点击?我遇到了麻烦,因为有这些行div的多个,我想能够添加行旁边的div行,并只删除该行。

+0

你还可以添加所需的HTML一旦被点击? –

+0

所以你试图让'+'按钮克隆当前行并追加它,'-'按钮删除被点击的行,对吗? –

回答

2

要做到这一点,你需要使用委托的事件处理程序为button元素将被动态地添加到DOM。从那里,您可以使用closest()分别查找该行以及clone()append()remove()

首先,添加类的按钮来进行识别它们更容易:

<button class="btn btn-primary btn-sm btn-add" type="button" data-button-action="addRow">+</button> 
<button class="btn btn-primary btn-sm btn-delete" type="button" data-button-action="deleteRow">-</button> 

然后你就可以将事件对他们说:

$('.parent-wrapper').on('click', '.btn-add', function() { 
    $(this).closest('.test-guided-search-row').clone().appendTo('.parent-wrapper'); 
}).on('click', '.btn-delete', function() { 
    $(this).closest('.test-guided-search-row').remove(); 
}); 

Example fiddle

1

找到你的行,克隆它,追加它。

$('.button').on('click', function() { 
    var row = $(this).closest('.test-guided-search-row').clone(); 
    $('.parent-wrapper').append(row); 
}) 

找到你的行,删除它。 删除

$('.button').on('click', function() { 
    var row = $(this).closest('.test-guided-search-row').remove(); 
}) 

//你需要定义什么键+是什么按钮 - 一个类名

0

如果你希望能够要在特定的div行旁边添加行并只删除该行,您需要为每个ID添加一个数字

这可能帮助: 通

$(this).closest('.new-wrapper')[0].id 

到addRow(ROWID)+按钮点击时。

function addRow(rowId){ 
    var next = rowId+1; 
    $(".parent-wrapper #rowId").after('<div id="'+next+'" class = "new-wrapper"> $(".test-guided-search-row").html() </div>); 
} 
1
$('.parent-wrapper').on('click', '.btn-add', function() { 
    var row = $(this).closest('.test-guided-search-row').clone(); 
    $(this).closest('.test-guided-search-row').after(row); 
}).on('click', '.btn-delete', function() { 
    $(this).closest('.test-guided-search-row').remove(); 
}); 

这究竟解决了我的问题。我想追加到最近的按钮点击行。