【问题标题】:How can I create an autocomplete box for the tag input?如何为标签输入创建自动完成框?
【发布时间】:2017-01-29 01:17:47
【问题描述】:

这是我的代码:

$(function(){

  $("#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|32)/.test(ev.which)) $(this).focusout(); 
    }
  });
  $('#tags').on('click', 'span', function() {
    if(confirm("Remove "+ $(this).text() +"?")) $(this).remove(); 
  });

});
#tags{
  float:right;
  border:1px solid #ccc;
  padding:5px;
  font-family:Arial;
}
#tags > span{
  cursor:pointer;
  display:block;
  float:right;
  color:#3e6d8e;
  background:#E1ECF4;
  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{
  direction: rtl;
  background:#eee;
  border:0;
  margin:4px;
  padding:7px;
  width:auto;
}
.autocomplete{
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="tags">
  <span>php</span>
  <input type="text" value="" placeholder="Add a tag" />
  <div class="autocomplete"></div>
</div>

如您所见,我正在尝试为帖子创建标签附件框。现在我需要为标签创建一个 autocomplete 框。我可以通过 jQuery UI 做到这一点,但我不想这样做。因为仅仅为了自动完成而使用 jQuery UI 似乎并不划算。

无论如何我想建议用户使用以下数组的值:

var tags = ["PHP", "MySQL", "HTML", "CSS", "C", "SQL", "JavaScript"];

例如:

  • 如果用户写H,我想建议他:HTML
  • 如果用户写T,我想建议他:HTMLJavaScript
  • 如果用户写SQ,我想建议他:MySQLSQL

好的,不使用 jQuery UI 是否可以做到这一点?

【问题讨论】:

  • 根据您的专业水平,我认为这对您来说是不可能的。下面的解决方案定义了一个函数自动完成。这将返回一个匹配标签的数组。在您的示例中,您将在 keyup 事件上调用此函数并显示从该函数返回的结果。

标签: javascript jquery html css


【解决方案1】:

试试这个:

var tags = ["PHP", "MySQL", "HTML", "CSS", "C", "SQL", "JavaScript"];

var searchTerm = 'SQ';

var matches = tags.filter(function(tag) {
    return tag.toLowerCase().indexOf(searchTerm.toLowerCase()) >= 0;
});

console.log(matches);

【讨论】:

  • 我不明白为什么我们在这里投反对票...我不是要解决问题,但它正在朝着正确的方向发展。 OP 还是应该在这里学到一些东西
【解决方案2】:

一个简单的方法是使用 Array.filter

你需要一个 polyfill 来支持 IE 浏览器

var tags = ["PHP", "MySQL", "HTML", "CSS", "C", "SQL", "JavaScript"];
function autocomplete(query) {
  var re = new RegExp(query,"gi");
  return tags.filter(function(tag){
    return re.exec(tag) 
  })
}

autocomplete('h')

【讨论】:

    猜你喜欢
    • 2016-08-18
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多