使用来自 API - 语义 UI 的结果更改下拉菜单项格式

Change dropdown menu items format using results from API - Semantic UI

目前正在设置一个下拉菜单,用于收集 API 的结果。我已经设置如下:

$("#my-dropdown").dropdown({
    minCharacters: 2,
    apiSettings: {
        cache: false,
        url: getCorrectUrl(),
        method: 'POST',
        onResponse: function(users) {
            var response = {
                success: true,
                results: []
            };
            $.each(users, function(index, item) {
                response.results.push({
                    name: item.name,
                    value: item.id
                });
            });
            return response;
        }
    }
});

它返回了正确的数据,只是不是我想要的形式。我想按我想要的方式格式化菜单项

具体来说,我目前得到的是:

...但我想要的是:

我看过 this question 的答案,它使用 onShow 函数将项目更改为自定义表单,但是手动操作 DOM 是唯一的方法做吗?或者是否有内置方法来指定自定义格式菜单项以用于 API 驱动的下拉菜单?

我以前做过这个,它涉及定义模板的自定义类型,用于为响应结果生成 HTML。

我会转到 Semantic/components 目录中的 dropdown.js 并找到:

$.fn.dropdown.settings.templates = { //line 3715 in version 2.2

您会在那里找到一些关于如何使用 JSON 生成结果的预定义模板。

我没有在那里编辑代码,而是复制了通常的结果模板 (templates.dropdown),调整了复制的包含的 js 以适合我的结果,并在我自己的 js 文件中从中创建了我自己的函数:

function addDropdownTemplate(name){
    $.fn.dropdown.settings.templates[name] = function (response) {//use response
    //use the edited version of the default template here    
}
}

当您调用上述函数时,您将添加自己的模板以将响应转换为 HTML 结果,要使用它只需指定您将在 api 中使用的模板类型设置:

apiSettings: {
   //your other settings as in the question above
   type: 'imageResult' //imageResult is an example, you can call it whatever 
   //you like as long as it's the same as what you passed
   //to your function as the name parameter
   }

我正在查看我的代码,我什至没有在 apiSettings 中附加 onResponse 事件,这是没有必要的。

遇到同样的问题,我遇到了 post 并尝试应用最佳答案解决方案,但未能成功。 但是,它让我发现了另一种方法来实现你想要做的事情,使用 "apiSettings":

下的 "onSuccess" 回调

$('.player-dropdown.remote').dropdown({
  on: 'click',
  direction: 'downward',
        allowAdditions: false,
        allowReselection: true,
        fireOnInit: false,
        apiSettings: {
            url: 'search?q={query}',
            onSuccess: function(response) {
             var html   = '' ;
             $('.player-member-menu').empty();
       $.each(response.results, function(index, item) {
         html += '<span class="select-player nowrap item " data-value="' + item.value + '">' 
         + '<small class="description right-floated">' + item.description + '</small>'
         + '<span class="text">' + item.name + '</span>' 
         + '</span>';
       });
       $(this).find('.player-member-menu').html(html) ;
      },
        },
        minCharacters : 3,
        searchDelay: 500,
        duration: 500,
        saveRemoteData: false,
        filterRemoteData: false,
        showOnFocus: true,
        fullTextSearch: true,
    });
在我的例子中,结果数组按照文档中的要求格式化,除了每个项目有 3 个参数而不是 2 个:名称、值和描述。