在Bootstrap中动态添加/删除选项卡 – 激活创建的选项卡
以下是动态添加/删除引导选项卡的代码段。 一切正常,但我希望新创建的选项卡处于活动状态并且处于焦点,而不是用于动态添加选项卡的选项卡。
这是小提琴: http : //jsfiddle.net/isherwood/F33Av/4/
这是有问题的代码:
HTML:
Contact Form: Joe Smith Contact Form: Molly Lewis
JS:
$(".nav-tabs").on("click", "a", function(e){ e.preventDefault(); $(this).tab('show'); }) .on("click", "span", function () { var anchor = $(this).siblings('a'); $(anchor.attr('href')).remove(); $(this).parent().remove(); $(".nav-tabs li").children('a').first().click(); }); $('.add-contact').click(function(e) { e.preventDefault(); var id = $(".nav-tabs").children().length; //think about it ;) $(this).closest('li').before('New Tabx '); $('.tab-content').append('Contact Form: New Contact '+id+''); });
CSS:
@import url('http://getbootstrap.com/2.3.2/assets/css/bootstrap.css'); .container { margin-top: 10px; } .nav-tabs > li { position:relative; } .nav-tabs > li > a { display:inline-block; } .nav-tabs > li > span { display:none; cursor:pointer; position:absolute; right: 6px; top: 8px; color: red; } .nav-tabs > li:hover > span { display: inline-block; }
这是一个解决方案:
见JSFiddle
-
单击“添加联系人”导航链接时仍会调用
tab('show')
。 即使调用了show tab函数,也没有显示任何选项卡内容,因为它没有链接到它的现有内容。 我所做的是添加一个条件来停止激活该选项卡。$(".nav-tabs").on("click", "a", function (e) { e.preventDefault(); if (!$(this).hasClass('add-contact')) { $(this).tab('show'); } })
-
我还将
data-toggle="tab"
属性删除到“添加联系人”navlink。 出于某种原因,它会激活“添加联系人”选项卡(如果有)。- + Add Contact
-
添加新选项卡后,触发
click
新选项卡,以便调用tab('show')
函数。 ( 见1 )$('.add-contact').click(function (e) { e.preventDefault(); var id = $(".nav-tabs").children().length; //think about it ;) var tabId = 'contact_' + id; $(this).closest('li').before('
- New Tab x
'); $('.tab-content').append('Contact Form: New Contact ' + id + ''); // add this $('.nav-tabs li:nth-child(' + id + ') a').click(); });
这是其他解决方案,我在互联网上找到了它
JS档案:
$('#btnAdd').click(function (e) { var nextTab = $('#tabs li').size()+1; // create the tab $('Tab '+nextTab+' ').appendTo('#tabs'); // create the tab content $('tab' +nextTab+' content').appendTo('.tab-content'); // make the new tab active $('#tabs a:last').tab('show'); });
html文件:
在这里进行演示和编辑https://www.bootply.com/61679