2015-01-12 14 views
0

我試圖在jQuery中構建一些下拉菜單。我正在努力獲得綁定到我添加的html的 $('。dropdown-toggle')。dropdown()。如何綁定引導下拉列表在jQuery中創建的HTML,然後附加

我在這裏創建了一個小提琴演示問題。 我希望底部下降與上部下拉相同。

我使用普通的html標記創建了上拉下拉菜單。 我通過jquery創建了底部下拉菜單。

這裏是小提琴http://jsfiddle.net/hLqkLxrm/

fiddle describing problem

這裏是JavaScript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<script> 
 
    $(document).ready(function() { 
 

 
    var nestedjson = '['; 
 
    nestedjson += '{"name":"dogs","href":"#", "innerlist":['; 
 
    nestedjson += '{"name":"pug","href":"pug"},' 
 
    nestedjson += '{"name":"shitzu","href":"shitzu"}'; 
 
    nestedjson += ']},'; 
 
    nestedjson += '{"name":"rodents","href":"#", "innerlist":['; 
 
    nestedjson += '{"name":"mouse","href":"a"},'; 
 
    nestedjson += '{"name":"rat","href":"b"},'; 
 
    nestedjson += '{"name":"gerbil","href":"c"}'; 
 
    nestedjson += ']}]'; 
 

 

 

 
    var parsedjson = JSON.parse(nestedjson); 
 

 

 
    var myhtml = '<ul class="nav nav-pills">'; 
 

 

 
    $.each(parsedjson, function() { 
 
     myhtml += '<li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#">' + this.name + '<b class="caret"></b></a> '; 
 
     myhtml += '<ul class="dropdown-menu>'; 
 
     $.each(this.innerlist, function() { 
 
      myhtml += '<li><a tabindex="-1" href = "' + this.href + '">'; 
 
      myhtml += this.name + '</a></li>'; 
 
     }); 
 
     myhtml += '</ul>'; 
 
     myhtml += '</li>'; 
 
    }); 
 

 

 
    myhtml += '</ul>'; 
 

 

 
    $(myhtml).appendTo('body'); 
 

 
    // not sure how to bind the bootstrap dropdown to added components. 
 
    // this is not working 
 
    $('body').on("change", function() { 
 
     alert('appended'); 
 
     $('.dropdown-toggle').dropdown(); 
 
    }); 
 
    
 
    
 

 

 
}); 
 

 
    </script>

回答

0

在您$.each功能二號線的HTML格式不正確。

變化:

myhtml += '<ul class="dropdown-menu>'; 

要:

myhtml += '<ul class="dropdown-menu">'; 

而且,你不需要身體的變化「,因爲處理程序引導數據屬性將使到下拉切換。

演示http://www.bootply.com/kzXvjXuE5P

+0

謝謝你這麼多,固定它。 –

+0

有沒有辦法將這個問題標記爲答案? –

+0

是的..你點擊此答案左側的複選標記 – ZimSystem