如何使用jQuery制作“标签框”(文本input字段+用逗号分隔的标签)

我正在研究一个允许用户通过标签发布内容的web应用程序,但是事情是,如果用逗号分隔的标签和文本字段值仍然是相同的,用户会有所不同。

例如YouTube或StackOverflow,现在我不需要检查数据库或任何东西。

谢谢!

jsBin演示

像StackOverflow类似的东西:

在这里输入图像描述

  • 允许字母数字和+-.# (并修剪空格!)
  • 转换为小写
  • 自动创build焦点输出上的标签框input (添加更多|分隔的键码)
  • 点击删除标签框(带确认)
 $(function(){ // DOM ready // ::: TAGS BOX $("#tags input").on({ focusout : function() { var txt = this.value.replace(/[^a-z0-9\+\-\.\#]/ig,''); // allowed characters if(txt) $("<span/>", {text:txt.toLowerCase(), insertBefore:this}); this.value = ""; }, keyup : function(ev) { // if: comma|enter (delimit more keyCodes with | pipe) if(/(188|13)/.test(ev.which)) $(this).focusout(); } }); $('#tags').on('click', 'span', function() { if(confirm("Remove "+ $(this).text() +"?")) $(this).remove(); }); }); 
 #tags{ float:left; border:1px solid #ccc; padding:5px; font-family:Arial; } #tags > span{ cursor:pointer; display:block; float:left; color:#fff; background:#789; padding:5px; padding-right:25px; margin:4px; } #tags > span:hover{ opacity:0.7; } #tags > span:after{ position:absolute; content:"×"; border:1px solid; padding:2px 5px; margin-left:3px; font-size:11px; } #tags > input{ background:#eee; border:0; margin:4px; padding:7px; width:auto; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="tags"> <span>php</span> <span>c++</span> <span>jquery</span> <input type="text" value="" placeholder="Add a tag" /> </div> 

你不一定需要在这里重新发明轮子。 为此目的已经存在一些库/插件,其中之一是Guillermo Rauch的TextboxList 。 你可以在这里find一个示范。 它已经有自动完成支持和一个相当广泛的API,这是任何执行这个主要障碍将是。

原来的实现使用MooTools,但你可以在这里find一个由golive的jQuery版本。

把一个文本input到一个div中,然后检查按键(如逗号或空格键),如果它匹配的键附加一个新的跨度与标签详细信息的div与jQuery。

如果需要,我可以提供更多的细节或示例,但编码应该相当简单。

在select2列表中使用“标记支持”: https ://select2.github.io/examples.html

  $(".js-example-tags").select2({ tags: true })