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

解决jQuery tagsInput在Bootstrap模态框中无法正常工作的问题

解决Bootstrap模态框中jQuery tagsInput不生效的问题

嘿,我一眼就看出你遇到的问题啦!你的代码里有两个关键问题导致模态框中的tagsInput功能失效,咱们一步步来修复:

问题分析

  1. 重复ID冲突:你在页面和模态框里都用了id="input-tags",HTML里ID必须是唯一的,这会导致jQuery只能找到第一个匹配的元素,模态框里的输入框根本没被初始化。
  2. 初始化时机错误:Bootstrap模态框默认是隐藏状态,页面加载时直接调用初始化方法,插件无法正确绑定到隐藏的元素上。必须等模态框完全显示后,再初始化里面的tagsInput。

修复后的完整代码

<html lang="en">
<head>
<title>Jquery - input tags</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-tagsinput/1.3.6/jquery.tagsinput.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-tagsinput/1.3.6/jquery.tagsinput.min.js"></script>
</head>
<body style="background: #337AB7">
<div style="width: 500px; margin: 0px auto;">
<h2 style="font-family:cursive;">Jquery - input tags plugin example</h2>
<input name="tags" id="page-input-tags" style="width:500px !important" />
</div>
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<input name="tags" id="modal-input-tags" style="width:500px !important" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
// 初始化页面上的tagsInput
$('#page-input-tags').tagsInput();

// 监听模态框完全显示事件,初始化模态框内的tagsInput
$('#myModal').on('shown.bs.modal', function() {
  $('#modal-input-tags').tagsInput();
});
</script>
</body>
</html>

关键修改说明

  • 唯一ID设置:把页面内的输入框ID改为page-input-tags,模态框内的改为modal-input-tags,确保每个元素ID唯一,避免选择器冲突。
  • 模态框事件绑定:使用Bootstrap的shown.bs.modal事件,这个事件会在模态框完全渲染并显示后触发,此时再初始化插件,就能确保插件正确绑定到可见的输入框上。

这样修改后,页面和模态框里的tagsInput功能都能正常运行啦!

内容的提问来源于stack exchange,提问作者Samir Jana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 08:07:45