【问题标题】:Bootstrap multiple dropdown menus change corresponding button textBootstrap 多个下拉菜单更改对应的按钮文本
【发布时间】:2015-05-15 19:46:01
【问题描述】:

我有一个包含多个下拉列表的页面,如下所示:

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

我想将按钮文本更改为选定的元素值。我找到了这个帖子:How to Display Selected Item in Bootstrap Button Dropdown Title,它解释了如何检索所选项目的文本/值并更改按钮的文本,但是当页面上有更多下拉菜单时会出现问题,下面的脚本会更改标签对于页面上的所有按钮:

$(function(){    
    $(".dropdown-menu li a").click(function(){    
      $(".btn:first-child").text($(this).text());
      $(".btn:first-child").val($(this).text());
   });  
});

如何修改它以使其仅更改相应的下拉菜单按钮? 作为一个附带问题:真的没有简单的方法可以让&lt;select&gt; 在引导程序中使用开箱即用的下拉菜单进行类似行为吗?

【问题讨论】:

    标签: javascript jquery html css twitter-bootstrap


    【解决方案1】:

    您需要为您的 jQuery 选择器添加特异性。目前,您正在选择具有 .btn 类且是其父级的第一个子级的 所有 元素。你想要做的是获取当前元素的父元素.btn-group,然后在其中找到.btn:first-child。你可以这样做:

    $(function(){    
        $(".dropdown-menu li a").click(function(){    
            $(this).closest('.btn-group').find(".btn:first-child").text($(this).text());
            $(this).closest('.btn-group').find(".btn:first-child").val($(this).text());
        });  
    });
    

    【讨论】:

    • 小提琴会更好
    【解决方案2】:

    许多潜在解决方案之一,横向向上 DOM 找到它所在的组,然后定位组内的按钮。

    $(function(){    
        $(".dropdown-menu li a").click(function(){ 
          var target = $(this).closest('.btn-group').find('.btn:first-child')
          target.text($(this).text());
          target.val($(this).text());
       });  
    });
    

    【讨论】:

    • 小提琴会更好
    猜你喜欢
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    相关资源
    最近更新 更多