繁体   English   中英

删除重复的标签jQuery

[英]remove duplicated tags jquery

我有这段代码,我想查找重复的代码,如果找到了,我想提醒它已经存在,因此用户无法插入该单词/标签。 有人可以帮忙吗

 <div id="tags">
<span>a</span> <span>b</span>
                <input type="text" value="" class="paste" id="search"  placeholder="Add a tag" />
              </div>
<script>
  $("#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="";
      if (($('#tags span').length) >4) {
       $('#tags input').prop('disabled', true);
     }
    },

    keyup : function(ev) {
      // if: comma|enter|space (delimit more keyCodes with | pipe)
      if(/(188|13|32)/.test(ev.which)) $(this).focusout();
    }
  });

  $('#tags').on('click', 'span', function() {
    if(confirm("Remove "+ $(this).text() +"?")) $(this).remove();
     $('#tags input').prop('disabled', false);
  });

});

</script>

DEMO

您可以具有添加标签的映射,在添加标签之前,请检查其是否存在:

 $(function() { // DOM ready // ::: TAGS BOX // added tags (mark 'a' and 'b' as already added) let tags = { 'a': true, 'b': true }; $("#tags input").on({ focusout: function() { var txt = this.value.replace(/[^a-z0-9\\+\\-\\.\\#]/ig, ''); // allowed characters if (txt) { if (tags[txt]) { // if the tag already exists show an error console.log(txt + ' already exists'); } else { $("<span/>", { text: txt.toLowerCase(), insertBefore: this }); tags[txt] = true; // add the tag } } this.value = ""; if (($('#tags span').length) > 4) { $('#tags input').prop('disabled', true); } }, keyup: function(ev) { // if: comma|enter|space (delimit more keyCodes with | pipe) if (/(188|13|32)/.test(ev.which)) $(this).focusout(); } }); $('#tags').on('click', 'span', function() { if (confirm("Remove " + $(this).text() + "?")) { $(this).remove(); var text = $(this).text(); tags[text] = false; // remove the tag } $('#tags input').prop('disabled', false); }); }); 
 #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="search-container"> <div id="tags"> <span>a</span> <span>b</span> <input type="text" value="" class="paste" id="search" placeholder="Add a tag" /> </div> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM