【问题标题】:Handle Bootstrap dropdown event in jQuery在 jQuery 中处理 Bootstrap 下拉事件
【发布时间】:2019-04-25 20:22:29
【问题描述】:

我有 twitter bootstrap 下拉菜单的标记,如下所示

<div class="dropdown" style="width: 300px !important;">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
Source
</button>
<div class="dropdown-menu" id="SelectMe">
   <a class="dropdown-item" href="#">CLE</a>
   <a class="dropdown-item" href="#">SQL</a>
   <a class="dropdown-item" href="#">FFILE</a>
   <a class="dropdown-item" href="#">SampleAPI</a>
</div>
</div>

现在,使用 jquery 在下拉列表中添加点击事件,如下所示

 $('.dropdown-menu a').click(function () {           
    alert("Hi")
  });

我的点击事件正在工作,但我无法更新下拉列表中的选定值。怎么做?

【问题讨论】:

  • 是否要将选中的文字设置为按钮文字?
  • @Kiranramchandran 是的
  • 查看答案

标签: javascript jquery twitter-bootstrap drop-down-menu


【解决方案1】:

$('.dropdown-menu a').click(function () {           
    $('button').text($(this).text());
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<div class="dropdown" style="width: 300px !important;">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
Source
</button>
<div class="dropdown-menu" id="SelectMe">
   <a class="dropdown-item" href="#">CLE</a>
   <a class="dropdown-item" href="#">SQL</a>
   <a class="dropdown-item" href="#">FFILE</a>
   <a class="dropdown-item" href="#">SampleAPI</a>
</div>
</div>

使用$('button').text($(this).text()); 为按钮设置值。

【讨论】:

    【解决方案2】:

    试试这个

    $('.dropdown-menu a').click(function () {           
        $('button[data-toggle="dropdown"]').text($(this).text());
    });
    

    DEMO HERE

    【讨论】:

      猜你喜欢
      • 2012-08-12
      • 2014-12-29
      • 1970-01-01
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      • 2014-04-08
      相关资源
      最近更新 更多