我有一个select2的问题,在我输入一个项目后我想再次使用相同的下拉列表,我似乎无法删除以前选择的项目
例如,假设我的id是"#StreamName",我认为这会清除它:
$("#StreamName").val(null).trigger("change");
但它似乎仍然显示以前选择的项目.从查看html看来,我通过这样做蛮力:
$("#select2-StreamName-container").html("");
但这似乎我没有正确使用API,所以我想看看是否有其他建议或我是否遗漏了一些东西.
看起来清除Select2的正确方法就是你的第一个建议,正如这个答案所暗示的那样.
$(document).ready(function() { $("#StreamName").select2(); $("#StreamName").val(null).trigger("change"); });
更新 - 远程数据源
JSFiddle使用远程数据
即使使用远程数据源,这仍然可以清除Select2输入:
$("#StreamName").val(null).trigger("change");
$(document).ready(function() { $("#StreamName").select2({ ajax: { url: "https://api.github.com/search/repositories", dataType: 'json', delay: 250, data: function(params) { return { q: params.term, // search term page: params.page }; }, processResults: function(data, params) { // parse the results into the format expected by Select2 // since we are using custom formatting functions we do not need to // alter the remote JSON data, except to indicate that infinite // scrolling can be used params.page = params.page || 1; return { results: data.items, pagination: { more: (params.page * 30) < data.total_count } }; }, cache: true }, escapeMarkup: function(markup) { return markup; }, // let our custom formatter work minimumInputLength: 1, templateResult: formatRepo, // omitted for brevity, see the source of this page templateSelection: formatRepoSelection // omitted for brevity, see the source of this page }); $("#StreamName").val(null).trigger("change"); // For testing... $('#set-null').click(function() { $("#StreamName").val(null).trigger("change"); }); }); function formatRepo(repo) { if (repo.loading) return repo.text; var markup = "" + "" + ""; return markup; } function formatRepoSelection(repo) { return repo.full_name || repo.text; }" + "" + repo.full_name + ""; if (repo.description) { markup += "" + repo.description + ""; } markup += "" + "" + "" + repo.forks_count + " Forks" + "" + repo.stargazers_count + " Stars" + "" + repo.watchers_count + " Watchers" + "