单击两次
第一次单击单元格会初始化 select2,第二次单击会告诉 select2 显示下拉列表。只需单击一次,您可以调用以下描述的 open 方法https://select2.org/programmatic-control/methods https://select2.org/programmatic-control/methodsselect2 初始化后。
// Initialise select2
let selectEle = cellEle.children("select").select2();
// Open the select2 dropdown
selectEle.select2('open');
替换选择
当点击一个值 select2 被销毁时,.html()
调用应该用所选值替换 select,但是它不能正常工作id
存储的值上不存在属性,这导致单元格恢复为正常选择。
处理的代码"select2:close"
事件包含行selectedValue = selectEle.select2('data')[0]['text'];
它放置第一个选定值的文本[0]
到变量中selectedValue
。此后,单元格的 HTML 会使用以下命令进行更新cellEle.html(selectedValue.id);
,但此时selectedValue
仅包含文本(例如“Alabama”),因此没有.id
财产。为了解决这个问题,ID 和 Text 都可以存储在数组中,然后在需要的地方使用,例如:
// Store the id and text of all selected values in the array
selectedValue = selectEle.select2('data').map(function(value) {
return { id: value.id, text: value.text };
});
// Get an array of IDs for the selected values (for preselecting values when select2 loads)
selectEle.val(states[cellId].map(function(value) { return value.id })).trigger('change');
// Get a comma separated string of the selected values (for populating the text in the cell)
cellEle.html(states[cellId].map(function(value) { return value.text; }).join(','));
多选模式-
允许多项选择的示例是https://jsfiddle.net/aqgbxz1d/ https://jsfiddle.net/aqgbxz1d/并也纳入下面的答案中。这似乎是基于的所需模式multiple="multiple"
问题中的财产。
该示例已更新为不再使用select2:close
事件。相反,它使用change
存储值变化的事件,以及第二个click
当用户单击页面上的其他位置时,文档上的事件处理程序会销毁 select2 下拉列表。考虑到您想要实现的目标,这似乎是一种更好的方法,因为它使选择保持开放状态以供选择多个值。
单选模式-
从评论来看,似乎可能需要单选模式。只允许进行单一选择的示例是https://jsfiddle.net/9jcnwbt2/1/ https://jsfiddle.net/9jcnwbt2/1/。如果需要单选模式,那么您需要:
- 删除多重属性
multiple="multiple"
- 添加空白选项
<option></option>
- 您还可以复制文档单击事件中的代码,该事件会销毁 select2 并将 HTML 更新到更改事件中。
(function ($) {
var states = [];
$(document).ready(function () {
$(".volunteer").on("click", function (e) {
// Check if select is already loaded
if (!$(this).has("select").length) {
var cellEle = $(this);
var cellId = this.id;
// Populate select element
cellEle.html(`<select class="js-example-basic" multiple="multiple">
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
</select>`);
// Initialise select2
let selectEle = cellEle.children("select").select2({placeholder: "Select a value"});
// Open the select dropdown so user doesn't have to click twice
selectEle.select2('open');
// Check if there is an existing value for this cell
if (states[cellId]) {
// preselect existing value
selectEle.val(states[cellId].map(function (value) {
return value.id
})).trigger('change');
}
// Attach event handler to store value changes
selectEle.on('change', function (e) {
// Get selected values
selectedValues = $(this).select2('data');
// Update the states array with id and text of selected
// values. The id is needed to restore the values if select2
// is reloaded on this cell. The text is required to generate
// the replacement text shown in the cell
states[cellId] = selectedValues.map(function (value) {
return {
id: value.id,
text: value.text
};
});
});
}
// Don't propagate the event
// This prevents this document click handler from executing which would
// remove select2 by calling destroy
e.stopPropagation();
});
});
// Attach event handler to document to capture any clicks
// This will be triggered for all clicks on the page, except those
// captured by the method described above this prevents this firing
// with e.stopPropagation()
// Which this is called select2 on any cells must be destoryed and their
// text value populated
$(document).on('click', function (e) {
// Loop through all select2 elements
$('.js-example-basic').each(function (idx) {
// Get the ID of the cell that's been selected
let cellId = $(this).parent().attr('id');
// Destroy select2 on this element
$(this).select2('destroy');
// Change html on the parent element (td) to just show the value
if(states[cellId] && states[cellId].length > 0){
$(this).parent().html(states[cellId].map(function (value) {
return value.text;
}).join(','));
} else {
$(this).parent().html("Select a value...")
}
});
});
})(jQuery)
.js-example-basic {
width: 200px;
}
thead{
font-weight: bold;
}
table, th, td {
border: 1px solid black;
}
tr {
height: 36px;
}
td {
width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected] /cdn-cgi/l/email-protection/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected] /cdn-cgi/l/email-protection/dist/css/select2.min.css" rel="stylesheet" />
<table>
<thead>
<tr>
<td>Table Header 1</td>
<td>Table Header 2</td>
</tr>
</thead>
<tbody>
<tr>
<td class="volunteer" id="47">Select a value...</td>
<td class=""></td>
</tr>
<tr>
<td class="volunteer" id="48">Select a value...</td>
<td class=""></td>
</tr>
</tbody>
</table>