버튼 클릭 시 tab 추가
1. html
<div class="container">
<div class="row">
<div class="col-md-12">
<p>
<button id="btn-add-tab" type="button" class="btn btn-primary pull-right">Add Tab</button>
</p>
<!-- Nav tabs -->
<ul id="tab-list" class="nav nav-tabs" role="tablist">
<li class="active"><a href="#tab1" role="tab" data-toggle="tab"><span>Tab 1 </span><span class="glyphicon glyphicon-pencil text-muted edit"></span></a></li>
</ul>
<!-- Tab panes -->
<div id="tab-content" class="tab-content">
<div class="tab-pane fade in active" id="tab1">Tab 1 content</div>
</div>
</div>
</div>
</div>
- ul : tab list
- li : tab list 각 요소
- tab-content : tab의 내용
2. js
var button='<button class="close" type="button" title="Remove this page">×</button>';
var tabID = 1;
function resetTab(){
var tabs=$("#tab-list li:not(:first)");
var len=1
$(tabs).each(function(k,v){
len++;
$(this).find('a').html('Tab ' + len + button);
})
tabID--;
}
$(document).ready(function() {
$('#btn-add-tab').click(function() {
tabID++;
$('#tab-list').append($('<li><a href="#tab' + tabID + '" role="tab" data-toggle="tab"><span>Tab ' + tabID + '</span> <span class="glyphicon glyphicon-pencil text-muted edit"></span> <button class="close" type="button" title="Remove this page">×</button></a></li>'));
$('#tab-content').append($('<div class="tab-pane fade" id="tab' + tabID + '">Tab ' + tabID + ' content</div>'));
$(".edit").click(editHandler);
});
$('#tab-list').on('click', '.close', function() {
var tabID = $(this).parents('a').attr('href');
$(this).parents('li').remove();
$(tabID).remove();
//display first tab
var tabFirst = $('#tab-list a:first');
resetTab();
tabFirst.tab('show');
});
var list = document.getElementById("tab-list");
});
var editHandler = function() {
var t = $(this);
t.css("visibility", "hidden");
$(this).prev().attr("contenteditable", "true").focusout(function() {
$(this).removeAttr("contenteditable").off("focusout");
t.css("visibility", "visible");
});
};
$(".edit").click(editHandler);
- tab ID : 고유 id 값 부여
- resetTab() : tab 삭제시 tab ID 값이 1씩 줄어듬
- btn-add-tab click : 추가 버튼 클릭시 tab 생성 (tab 이름, edit 버튼, close 버튼)
(출처 : https://www.codeply.com/go/4yGNCaA8Xs/bootstrap-tabs-add-edit-remove)
'개발일지 > Javascript & jQuery' 카테고리의 다른 글
[Javascript] table pagination (paging) (0) | 2020.06.10 |
---|---|
[Javascript] 시군구 select box (1) | 2020.05.22 |
[Javascript] MQTT 웹소켓 통신 (0) | 2020.04.02 |
[Javascript] 화면 이미지(png)로 저장 (0) | 2020.03.23 |
[Javascript] 화면 PDF로 저장 (2) | 2020.03.19 |