单击bootstrap下拉元素并更改值

时间:2017-06-08 10:01:01

标签: php jquery twitter-bootstrap

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

我得到了一个包含aand itry的列表来获取点击事件但没有完成任务

$(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();
      });
}

2 个答案:

答案 0 :(得分:2)

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

// $(".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');
});

答案 1 :(得分:0)

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

更改点击事件,如下所示:

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