Bootstrap Tags Input达到maxTags上限时如何显示提示弹窗?
Hey 👋 这个需求其实Bootstrap Tags Input本身没自带弹窗提示,但咱们可以通过它提供的事件轻松实现,给你分享两种靠谱的解决办法:
方案1:利用
beforeItemAdd事件拦截并提示 Bootstrap Tags Input内置了beforeItemAdd事件——它会在新标签被添加之前触发,刚好适合咱们在这里做数量校验。
结合你的代码,只需要加一段事件监听逻辑就行:
// 假设你已经初始化了Bloodhound和tagsinput var languages = new Bloodhound({ // 你的数据源配置... }); $('#language-input').tagsinput({ maxTags: 10, typeaheadjs: { source: languages.ttAdapter() } }); // 监听标签添加前的事件 $('#language-input').on('beforeItemAdd', function(event) { // 获取当前已选中的标签数量 const currentTagCount = $(this).tagsinput('items').length; // 判断是否达到上限 if (currentTagCount >= 10) { // 阻止新标签被添加 event.cancel = true; // 弹出提示,这里用原生alert或者Bootstrap组件都可以 alert('最多只能选择10种语言哦!'); // 要是想用更美观的Bootstrap模态框,示例如下(需确保引入Bootstrap模态框组件): // $('#max-tags-modal').modal('show'); } });
方案2:自定义提示样式(比如Bootstrap Toast)
如果觉得原生alert太生硬,也可以换成Bootstrap的Toast组件来做更优雅的提示,只需要把上面的alert部分替换成Toast的调用即可:
<!-- 先在HTML里定义Toast结构 --> <div class="toast position-fixed bottom-0 end-0 m-3" role="alert" aria-live="assertive" aria-atomic="true"> <div class="toast-header"> <strong class="me-auto">提示</strong> <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button> </div> <div class="toast-body"> 最多只能选择10种语言哦! </div> </div>
// 然后在事件监听里调用 $('#language-input').on('beforeItemAdd', function(event) { const currentTagCount = $(this).tagsinput('items').length; if (currentTagCount >= 10) { event.cancel = true; // 显示Toast const toastEl = document.querySelector('.toast'); const toast = new bootstrap.Toast(toastEl); toast.show(); } });
关键说明
beforeItemAdd是官方提供的事件,完全兼容原有功能,不会有兼容性问题$(this).tagsinput('items')可以获取当前所有已选中的标签数组,通过length就能拿到数量- 提示弹窗可以根据你的项目风格自由替换,比如用SweetAlert、Element UI的Message组件等都可以
内容的提问来源于stack exchange,提问作者acmsohail
相关产品推荐
相关产品推荐

