jQuery 如何在 Bootstrap 按钮下拉标题中显示所选项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13437446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:37:34  来源:igfitidea点击:

How to Display Selected Item in Bootstrap Button Dropdown Title

jquerytwitter-bootstrap

提问by Suffii

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

我在我的应用程序中使用 bootstrap Dropdown 组件,如下所示:

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

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").

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

采纳答案by Jai

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

据我了解您的问题是您想使用单击链接文本更改按钮的文本,如果是这样,您可以尝试这个: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.

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

so you have to delegate the event to the closest static parent with .on()jQuery method:

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

 $(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.

这里的 event 被委托给 static parent $(".dropdown-menu"),尽管您也可以将事件委托给 the ,$(document)因为它始终可用。

回答by cmcculloh

Updated for Bootstrap 3.3.4:

针对 Bootstrap 3.3.4 更新:

This will allow you to have different display text and data value for each element. It will also persist the caret on selection.

这将允许您为每个元素使用不同的显示文本和数据值。它还将在选择时保留插入符。

JS:

JS:

$(".dropdown-menu li a").click(function(){
  $(this).parents(".dropdown").find('.btn').html($(this).text() + ' <span class="caret"></span>');
  $(this).parents(".dropdown").find('.btn').val($(this).data('value'));
});

HTML:

HTML:

<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
    Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
    <li><a href="#" data-value="action">Action</a></li>
    <li><a href="#" data-value="another action">Another action</a></li>
    <li><a href="#" data-value="something else here">Something else here</a></li>
    <li><a href="#" data-value="separated link">Separated link</a></li>
  </ul>
</div>

JS Fiddle Example

JS小提琴示例

回答by Kyle Crossman

I was able to slightly improve Jai's answer to work in the case of you having more than one button dropdown with a pretty good presentation that works with bootstrap 3:

我能够稍微改进 Jai 的工作答案,如果您有一个以上的按钮下拉列表,并且具有与 bootstrap 3 一起使用的非常好的演示文稿:

Code for The Button

按钮代码

<div class="btn-group">
  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
    Option: <span class="selection">Option 1</span><span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu">
    <li><a href="#">Option 1</a></li>
    <li><a href="#">Option 2</a></li>
    <li><a href="#">Option 3</a></li>
  </ul>
</div>

JQuery Snippet

JQuery 代码段

$(".dropdown-menu li a").click(function(){

  $(this).parents(".btn-group").find('.selection').text($(this).text());
  $(this).parents(".btn-group").find('.selection').val($(this).text());

});

I also added a 5px margin-right to the "selection" class.

我还在“选择”类中添加了一个 5px 的边距。

回答by Mangirdas Skripka

This single jQuery function will do all you need.

这个单一的 jQuery 函数将满足您的所有需求。

$( document ).ready(function() {
    $('.dropdown').each(function (key, dropdown) {
        var $dropdown = $(dropdown);
        $dropdown.find('.dropdown-menu a').on('click', function () {
            $dropdown.find('button').text($(this).text()).append(' <span class="caret"></span>');
        });
    });
});

回答by WonderBoy

This one works on more than one dropdown in the same page. Furthermore, I added caret on selected item:

这个适用于同一页面中的多个下拉列表。此外,我在所选项目上添加了插入符号:

    $(".dropdown-menu").on('click', 'li a', function(){
        $(this).parent().parent().siblings(".btn:first-child").html($(this).text()+' <span class="caret"></span>');
        $(this).parent().parent().siblings(".btn:first-child").val($(this).text());
    });

回答by Oskar

Here is my version of this which I hope can save some of your time :)

这是我的版本,希望可以节省您的一些时间:)

enter image description herejQuery PART:

在此处输入图片说明jQuery 部分:

$(".dropdown-menu").on('click', 'li a', function(){
  var selText = $(this).children("h4").html();


 $(this).parent('li').siblings().removeClass('active');
    $('#vl').val($(this).attr('data-value'));
  $(this).parents('.btn-group').find('.selection').html(selText);
  $(this).parents('li').addClass("active");
});

HTML PART:

HTML 部分:

<div class="container">
  <div class="btn-group">
    <a class="btn btn-default dropdown-toggle btn-blog " data-toggle="dropdown" href="#" id="dropdownMenu1" style="width:200px;"><span class="selection pull-left">Select an option </span> 
      <span class="pull-right glyphiconglyphicon-chevron-down caret" style="float:right;margin-top:10px;"></span></a>

     <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
       <li><a href="#" class="" data-value=1><p> HER Can you write extra text or <b>HTLM</b></p> <h4> <span class="glyphicon glyphicon-plane"></span>  <span> Your Option 1</span> </h4></a>  </li>
       <li><a href="#" class="" data-value=2><p> HER Can you write extra text or <i>HTLM</i> or some long long long long long long long long long long text </p><h4> <span class="glyphicon glyphicon-briefcase"></span> <span>Your Option 2</span>  </h4></a>
      </li>
      <li class="divider"></li>
   <li><a href="#" class="" data-value=3><p> HER Can you write extra text or <b>HTLM</b> or some </p><h4> <span class="glyphicon glyphicon-heart text-danger"></span> <span>Your Option 3</span>  </h4></a>
      </li>
    </ul>
  </div>
  <input type="text" id="vl" />
</div>  

回答by NullPoiиteя

you need to use add class openin <div class="btn-group open">

你需要使用添加类open<div class="btn-group open">

and in liadd class="active"

li补充class="active"

回答by ken

Further modified based on answer from @Kyle as $.text() returns exact string, so the caret tag is printed literally, than as a markup, just in case someone would like to keep the caret intact in dropdown.

根据@Kyle 的答案进一步修改为 $.text() 返回精确的字符串,因此插入符号按字面打印,而不是作为标记,以防万一有人希望在下拉列表中保持插入符号完整。

$(".dropdown-menu li").click(function(){
  $(this).parents(".btn-group").find('.btn').html(
  $(this).text()+" <span class=\"caret\"></span>"
  );
});

回答by Hitham S. AlQadheeb

Another simple way (Bootstrap 4) to work with multiple dropdowns

使用多个下拉列表的另一种简单方法(Bootstrap 4)

    $('.dropdown-item').on('click',  function(){
        var btnObj = $(this).parent().siblings('button');
        $(btnObj).text($(this).text());
        $(btnObj).val($(this).text());
    });

回答by Sergio Promov

I have corrected script for multiple dropdowns on the page

我已经更正了页面上多个下拉菜单的脚本

$(function(){
    $(".dropdown-menu li a").click(function(){
        var item = $(this);
        var id = item.parent().parent().attr("aria-labelledby");

        $("#"+id+":first-child").text($(this).text());
        $("#"+id+":first-child").val($(this).text());
   });
});