【问题标题】:Click on bootstrap dropdown element and change the value单击引导下拉元素并更改值
【发布时间】:2017-06-08 10:01:00
【问题描述】:

这是dropdwon

<div class="col-md-6">
             <div class="dropdown">
                <input  type="text" data-toggle="dropdown" id="search-input" class="form-control">
                <ul class="dropdown-menu" id="employee-list">
                  <!--filled by ajax -->
                </ul>
              </div>
        </div>

我得到一个列表,并尝试获取点击事件,但没有完成

$(document).ready( function(){
    $('#search-input').keyup(function(e){
        if($(this).val().length >= 3 /*&& e.which != 8*/ ){
            get_users($(this).val());
        }
    });

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

需要单击列表元素并将输入的文本设置为单击元素的文本,但我无法处理单击事件

function get_users($text){
    $.ajax({
      url: "asociate_ci.php",
      method: 'get',
      data: {
        'text': $text ,
        'option':'get_users' 
      }
    })
      .done(function( response ) {
        var employees = JSON.parse(response);
        //console.dir(employees);
        $('#employee-list').empty();
        $.each(employees, function(){
            //console.log(this.last_name);
            $('#employee-list').append("<li ><a class='employee-li'>"+this.last_name+"</a></li>");
        });
        $('#search-input').focus();
      });
}

【问题讨论】:

  • 使用$(document).on('click',".dropdown-menu li a",function() { ... }); 动态添加元素。
  • 检查我的答案 af_doubts

标签: php jquery twitter-bootstrap


【解决方案1】:

对于匹配选择器.dropdown-menu 的所有元素,您需要使用单个处理程序a 使用on。这将能够绑定到动态创建的元素。

// $(".dropdown-menu") = watch for any changes to the dom inside this element
// 'click' = event type
// a = add click event to these elements
$('.dropdown-menu').on('click', 'a', function(){
    alert('aaaa');
});

【讨论】:

    【解决方案2】:

    当前元素上的 jquery 处理程序可以正常工作, 但是新元素没有绑定到这些处理程序,所以这就是我们需要使用 .on() 方法的原因。

    如下改变你的点击事件:

    $('.dropdown-menu').on('click', 'a', function(){
       alert('aaaa');
    });
    

    【讨论】:

    • 由于性能问题,最好使用特定的选择器而不是整个 document。这家伙解释得很好:stackoverflow.com/a/12824698/8085668。我想你知道这一点,我只是想我会为其他人提及它。
    猜你喜欢
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多