[select2] 自定义下拉内容格式
<html> <header> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> </header> <body> <select id="select2Dropdown"></select> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.js"></script> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <script> let data = []; for (var i = 0; i < 10; i++) { data.push({ id: i, text: `text${i}` }); } $("#select2Dropdown").select2( { data: data, width: '100%', escapeMarkup: function (markup) { return markup; }, templateResult: dataFormat }, ); function dataFormat(data) { if (data.loading) { return data.text; } return `<div>${data.id}</div><div>${data.text}</div>` } </script> </body> </html>
注:如果没有添加escapeMarkup,templateResult将返回文本内容,不会按html元素显示数据