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

如何使用Bootstrap Tags Input手动创建标签

当然可行!这正是Bootstrap Tags Input的核心功能之一,只是可能你没配置对触发选项或者不小心限制了自由输入。我来帮你快速搞定:

1. 先确认依赖加载顺序正确

Bootstrap Tags Input依赖jQuery和Bootstrap,确保你的页面加载顺序是这样的(顺序错了很容易出问题):

<!-- jQuery 必须最先加载 -->
<script src="jquery.min.js"></script>
<!-- Bootstrap 的样式和脚本 -->
<link rel="stylesheet" href="bootstrap.min.css">
<script src="bootstrap.min.js"></script>
<!-- Bootstrap Tags Input 的样式和核心脚本 -->
<link rel="stylesheet" href="bootstrap-tagsinput.css">
<script src="bootstrap-tagsinput.js"></script>

2. 配置触发添加标签的按键

默认情况下,插件只支持按回车添加标签,你需要手动把空格(键码32)和逗号(键码44)加入触发列表。初始化时加上confirmKeys选项即可:

$('input[name="tags"]').tagsinput({
  confirmKeys: [13, 32, 44] // 13=回车,32=空格,44=逗号
});

3. 确保允许自由输入

如果你之前配置了预定义标签的自动补全(比如用了source选项),可能不小心限制了只能选择已有标签。记得开启freeInput选项(默认是true,但如果手动修改过一定要设回来):

$('input[name="tags"]').tagsinput({
  confirmKeys: [13, 32, 44],
  freeInput: true // 允许用户输入自定义标签
});

4. 测试验证

现在输入任意文本,按空格或逗号,就能自动把输入内容转换成标签了——完全和Stack Overflow的标签功能一样!

额外小技巧(可选)

如果需要更定制化的体验,可以加上这些配置:

  • maxTags: 设置最多能添加的标签数量
  • onTagAdded/onTagRemoved: 标签添加/移除时的回调函数
  • tagClass: 自定义标签的样式类

示例:

$('input[name="tags"]').tagsinput({
  confirmKeys: [13, 32, 44],
  freeInput: true,
  maxTags: 8,
  tagClass: 'label label-primary',
  onTagAdded: function(tag) {
    console.log('新标签已添加:' + tag);
  }
});

内容的提问来源于stack exchange,提问作者Olivia Brown

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:17:26