Show dynamically created tab content in bootstrap

徘徊边缘 提交于 2019-12-12 04:52:44

问题


So I'm creating tabs dynamically in bootstrap using this example, everything is working fine BUT the new created tab is clicked but the content is never shown. I tried everyway that exists in javascript to show it but nothing. The tab-pane is never switched to active. Any idea anyone?

Ps: i'm including it in richfaces page.

My code:

$(document).on('click','#add.add-contact',function (e) {
                e.preventDefault();
                var id = $(".nav-pills").children().length; //think about it ;)
                var tabId = 'contact_0' + id;
                $(this).closest('li').before('<li><a href="#' + tabId + '" data-toggle="pill">New Tab</a></li>');
                $('.tab-content').append('<div class="tab-pane fade" id="' + tabId + '">Contact Form: New Contact ' + id + '</div>');
                $('.nav-pills li:nth-child(' + id + ') a').click();


            }); 

$(document).on('click', '#reportsDisplay.nav-pills a', function (e) {

            e.preventDefault();
            if (!$(this).hasClass('add-contact')) {
                $(this).tab('show');

            }

        })

<a4j:outputPanel styleClass="tabtable">
    <ul class="nav nav-pills" id="reportsDisplay">
        <li class="active"><a href="#contact_01" data-toggle="pill">Joe
                Smith</a></li>
        <li><a href="#contact_02" data-toggle="pill">Molly Lewis</a>
            </li>
        <li><a href="#" class="add-contact" id="add">+ Add
                Contact</a></li>
    </ul>
    <div class="tab-content">
        <div class="tab-pane fade active" id="contact_01">Contact Form:
            Joe Smith</div>
        <div class="tab-pane fade" id="contact_02">Contact Form: Molly
            Lewis</div>
        </div>
</a4j:outputPanel>

Update:

I've been debugging the javascript code and it seems that $(this).tab('show'); returns Undefined. I have no idea how to fix that.

Update: I wrote this function to do it manually

$(function(){

             $(document).on('click',"#contacts.nav-pills a", function (e) {
                e.preventDefault();
                var active_tab_selector = $('.tab-content > div.active');
                var target_tab_selector = '#'+$(this).attr('href').substr(1);
                $(active_tab_selector).removeClass('active in');
                $(target_tab_selector).addClass('active in');
            }); 
        });

But I get Empty string passed to getElementById(). for the line $(target_tab_selector).addClass('active in');. How to fix it?


回答1:


I found the error which is I needed to add this line : if (!$(this).hasClass('add-contact')) at the beginning of the function because the target_tab_selector value changes when I click on add and become empty.



来源:https://stackoverflow.com/questions/26799267/show-dynamically-created-tab-content-in-bootstrap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!