Dynamic dropdown menu with bootstrap not working

前端 未结 1 1431
粉色の甜心
粉色の甜心 2021-01-27 20:08

I have been using bootstrap for a while, and I came across an issue when trying to add a dropdown menu dynamically.

This is the JavaScript that I have:

$         


        
相关标签:
1条回答
  • 2021-01-27 20:30

    Here is a working jsFiddle: http://jsfiddle.net/szx4Y/85/.

    FYI, your jsFiddle didn't work because you didn't include the Bootstrap script file. So if you were doing any testing there that wouldn't have worked.

    I changed your code to call $(".dropdown-toggle").dropdown(); immediately after you append your HTML. By calling that method you are setting up the elements to handle all the Bootstrap functionality (click events, etc); there's no reason to call it every time you click your new element.

    Relevant Code

    HTML

    <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu" style="display: block; position: static; margin-bottom: 5px; *width: 180px;">
        <li><a tabindex="-1" href="#">Action</a></li>
        <li><a tabindex="-1" href="#">Another action</a></li>
        <li><a tabindex="-1" href="#">Something else here</a></li>
        <li class="divider"></li>
        <li class="dropdown-submenu pull-left"> <a tabindex="-1" href="#">More options</a>
            <ul class="dropdown-menu" id="mainMenu">
                <li><a tabindex="-1" href="#">Second level link</a></li>
                <li><a tabindex="-1" href="#">Second level link</a></li>
                <li><a tabindex="-1" href="#">Second level link</a></li>
                <li><a tabindex="-1" href="#">Second level link</a></li>
                <li><a tabindex="-1" href="#">Second level link</a></li>
            </ul>
        </li>
    </ul>
    
    <button id="clickHere">Click here </button>
    <div id="appendHere"></div>
    

    Javascript

    $(document).ready(function() {
        $("#clickHere").click(function(){
                $("#appendHere").html("<div class=\"dropdown\" style=\"display:inline;\"><a id=\"drop1\" href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\"><b class=\"caret\"></b></a><ul class=\"dropdown-menu pull-left\"><li><button>Analyse Now</button></li><li class=\"divider\"></li><li><button>Analyse Later</button></li></ul></div>");
        });
    
        $('.dropdown-toggle').dropdown();
    });
    

    CSS

    .dropdown-menu {
        float:right;
    }
    
    0 讨论(0)
提交回复
热议问题