如何在Bootstrap按钮下拉标题中显示所选项目 [英] How to Display Selected Item in Bootstrap Button Dropdown Title

查看:78
本文介绍了如何在Bootstrap按钮下拉标题中显示所选项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在像这样在我的应用程序中使用bootstrap Dropdown组件:

I am using the bootstrap Dropdown component in my application like this:

<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>

我想将所选项目显示为btn标签.换句话说,将请从列表中选择"替换为已选择的列表项(项目I",项目II",项目III").

I would like to display the selected item as the btn label. In other words, replace "Please Select From List" with the list item that has been selected("Item I", "Item II", "Item III").

推荐答案

据我了解,您的问题是您希望使用单击链接的文本来更改按钮的文本,如果可以的话,您可以尝试以下操作: http://jsbin.com/owuyix/4/edit

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:

当我有通过ajax调用填充的列表项<li>时,这对我不起作用.

this doesn't work for me when I have lists item <li> populated through ajax call.

所以您必须使用.on() jQuery方法将事件委托给最近的静态父级:

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());
   });

});

这里的事件委托给静态父对象$(".dropdown-menu"),尽管您也可以将事件委托给$(document),因为它总是可用的.

Here event is delegated to static parent $(".dropdown-menu"), although you can delegate the event to the $(document) too because it is always available.

这篇关于如何在Bootstrap按钮下拉标题中显示所选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆