bootstrap 範行:
<div class="btn-group">
<button class="btn">Please Select From List</button>
<button class="btn dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
<li><a tabindex="-1" href="#">Item I</a></li>
<li><a tabindex="-1" href="#">Item II</a></li>
<li><a tabindex="-1" href="#">Item III</a></li>
<li class="divider"></li>
<li><a tabindex="-1" href="#">Other</a></li>
</ul>
</div>
bootstrap v3.3 官方教學:
https://getbootstrap.com/docs/3.3/components/#dropdowns
問題是,下拉式 button ,希望點選了 menu item 可以把選擇的項目,更新回顯用的元件的標題裡,官方提供的不會更新button 的title. 解法如下:
As far as i understood your issue is that you want to change the text of the button with the clicking linked text, if so you can try this one: http://jsbin.com/owuyix/4/edit
$(function(){
$(".dropdown-menu li a").click(function(){
$(".btn:first-child").text($(this).text());
$(".btn:first-child").val($(this).text());
});
});
As per your comment:
this doesn’t work for me when I have lists item <li>
populated through ajax call.
so you have to delegate the event to the closest static parent with .on()
jQuery method:
$(function(){
$(".dropdown-menu").on('click', 'li a', function(){
$(".btn:first-child").text($(this).text());
$(".btn:first-child").val($(this).text());
});
});
Here event is delegated to static parent $(".dropdown-menu")
, although you can delegate the event to the $(document)
too because it is always available.
我服用的 html:
<div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li><a href="#"> </a></li> <li><a href="#">Android</a></li> <li><a href="#">iOS</a></li> </ul> </div>
我服用的 javascript:
$(function(){ $(".dropdown-menu").on('click', 'li a', function(){ $(".btn:first-child").html($(this).text()+' <span class="caret"></span>'); }); });
如果有多組 dropdown list 我是使用:
html:
<div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" id="dropdownMenu1"> <span class="caret"></span> </button> <ul class="dropdown-menu" id="dropdownMenu1Item"> <li><a href="#"> </a></li> <li><a href="#">Android</a></li> <li><a href="#">iOS</a></li> </ul> </div>
javascript:
$(function(){ $("#dropdownMenu2Item").on('click', 'li a', function(){ var selText = $(this).text(); $("#dropdownMenu2:first-child").html(selText+' <span class="caret"></span>'); }); }); $(function(){ $("#dropdownMenu1Item").on('click', 'li a', function(){ var selText = $(this).text(); $("#dropdownMenu1:first-child").html(selText+' <span class="caret"></span>'); }); });
相關範例:
https://www.bootply.com/64302