You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Select2中formatNoMatches函数未被调用的问题?

解决Select2中formatNoMatches函数不生效的问题

你遇到的问题核心是Select2 4.x版本已废弃formatNoMatches配置项,改用language对象下的noMatches方法来定义无匹配结果时的显示内容,这就是你的函数从未被调用的原因。

具体修改方案

将原来的formatNoMatches函数迁移到配置的language属性中,命名为noMatches即可:

修改后的JavaScript代码

$(document).ready(function () {
    console.log("Prima");
    
    var options = {
        data: [{ id: 1, title: 'ciao', text: 'pippo ciao' }, { id: 2, title: 'ciao', text: 'pippo ciao' }],
        language: {
            noMatches: function () {
                console.log("Chiamata formatNoMatches");
                return "<a href='URL_DEL_LINK' target='_blank'>Nessun risultato trovato, clicca qui per ulteriori informazioni</a>";
            }
        }
    };
    console.log("Dopo");
    $("#pippo").select2(options);
    console.log("Fine");
});

HTML代码(无需修改,确保依赖引入正确)

<!doctype html>
<html lang="en">

<head>
    <title>Title</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet" />
</head>

<body>
    <select class="form-control" id="pippo"></select>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"></script>
    <script>
        // 上面修改后的JS代码放在此处
    </script>
</body>

</html>

验证方式

打开页面后点击Select2下拉框,输入一个不存在于现有选项中的内容(比如"test"),此时会触发noMatches函数,控制台会输出日志,同时下拉框会显示你定义的链接文本。

内容的提问来源于stack exchange,提问作者Emanuele Lucchese

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 15:00:54