且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Bootstrap中动态添加/删除选项卡 - 激活创建的选项卡

更新时间:2022-06-10 19:11:48

这是一个解决方案:


  1. code>标签('show')仍然在添加联系人点击了navlink。即使调用了show tab函数,也没有显示任何选项卡内容,因为它没有链接到它的现有内容。我做的是添加一个条件来停止激活该标签。

  1. The tab('show') is still being called when the "Add Contact" navlink is clicked. Even though the show tab function is called, no tab content is being displayed because it has no existing contents linked to it. What I did is to add a condition to stop activating that tab.

$(".nav-tabs").on("click", "a", function (e) {
     e.preventDefault();
     if (!$(this).hasClass('add-contact')) {
         $(this).tab('show');
     }
})


  • 我还将 data-toggle =tab属性移除到添加联系人navlink。出于某种原因,它会激活添加联系人标签(如果有)。

  • I also removed the data-toggle="tab" attribute to the "Add Contact" navlink. For some reason, it activates the "Add Contact" tab if it's there.

    <li><a href="#" class="add-contact">+ Add Contact</a></li>
    


  • 添加新标签后,触发点击$新选项卡的c $ c>,以便调用选项卡('show')函数。 (参见1

  • Upon adding a new tab, trigger the click of the new tab so that the tab('show') function will be called. (see 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('<li><a href="#contact_' + id + '">New Tab</a> <span>x</span></li>');
         $('.tab-content').append('<div class="tab-pane" id="' + tabId + '">Contact Form: New Contact ' + id + '</div>');
    
         // add this
         $('.nav-tabs li:nth-child(' + id + ') a').click();
    });