Bootstrap4下拉按钮 - 获取所选元素

时间:2017-10-26 10:05:25

标签: javascript bootstrap-4

我在Bootstrap4中有一个带有下拉列表的按钮。 HTML如下所示:

<div class="row" id="dropdown-box">
  <div class="col-lg-6">
    <div class="input-group">
      <div class="input-group-btn" id="button-group-id">
        <button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Select
        </button>
        <div class="dropdown-menu">
          {% for skill in skills %}
            <a class="dropdown-item" href="#">{{skill.name}}</a>
          {% endfor %}
        </div>
      </div>
      <input type="text" class="form-control" aria-label="Text input with dropdown button">
    </div>
  </div>

这是Javascript,没有效果:(

<script>
  $( document ).ready(function() {
      $("#button-group-id").on("show.bs.dropdown", function(event){
          var x = $(event.relatedTarget).text(); // Get the text of the element
          console.log(x);
      });

  });
</script>

1 个答案:

答案 0 :(得分:2)

尝试使用此js

$( document ).ready(function() {
     $(".dropdown-menu a").click(function(){
     var selText = $(this).text();
     console.log(selText);
    });
});

小提琴:https://jsfiddle.net/5rpwvzsw/