Chosen.js 在 keyup 上动态填充下拉菜单

Chosen.js dynamically populate dropdown on keyup

我几乎成功地在下拉菜单中实现了 Chosen.js。我的代码在这里:

$('#skills_chosen').on('change', function(){
    var items="";
    var typedOpt = $('#skills_chosen').val();
    $.getJSON("php/skillList.php", {term:typedOpt}, function(skillList){
    $.each(skillList,function(index,item) 
    {
      items+="<option value='"+item.skill+"'>"+item.skill+"</option>";
    });
    $("#skills").append(items); 
    $('.chzn-select').trigger("chosen:updated");
    });

});

我遇到了一个小问题。只有在 select 框失去焦点后,下拉菜单才会触发 ajax 调用,并且只有在 select 框重新获得焦点后,选项才可用。这显然不是很友好。

我尝试将事件触发器更改为

$('#skills_chosen').on('keyup', function(){

以及按键、按键。这些都是第一次工作,但它们会清空文本区域,因此只能输入一个字符。这让我发疯。

我还尝试包装 ajax 调用以在页面加载时填充 select 框,预填充 select 选项。这会停止 select 选项框的工作。如果我在 select 选项更新后尝试保留 "text field" 中保留的内容,这没有什么不同。

我做错了什么,我怎样才能在 select 框第一次获得焦点并且用户开始输入时让它工作?

点击事件呢?

    $('#skills_chosen').on('click change', function(){
        var items="";
        var typedOpt = $('#skills_chosen').val();
        $.getJSON("php/skillList.php", {term:typedOpt}, function(skillList){
        $.each(skillList,function(index,item) 
        {
          items+="<option value='"+item.skill+"'>"+item.skill+"</option>";
        });
        $("#skills").append(items); 
        $('.chzn-select').trigger("chosen:updated");
        });

    }) ;
 $('#skills_chosen').on('click change', function(){
    var items="";
    var typedOpt = $('#skills_chosen').val();
    $.getJSON("php/skillList.php", {term:typedOpt}, function(skillList){
    $.each(skillList,function(index,item) 
    {
      items+="<option value='"+item.skill+"'>"+item.skill+"</option>";
    });
    $("#skills").append(items); 
    $('.chzn-select').trigger("chosen:updated");
    });

}) ;

@madalin ivascu 这是一种享受,谢谢 :)