如何为标签输入创建自动完成框? [英] How can I create an autocomplete box for the tag input?

查看:67
本文介绍了如何为标签输入创建自动完成框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

$(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用于自动完成功能似乎负担不起.

As you see, I'm trying to create a tag attachment box for a post. Now I need to create an autocomplete box for tags. I can do that by jQuery UI, but I don't want to. Because using jQuery UI just for autocomplete doesn't seem affordable.

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

Anyway I want to suggest to user the values of following array:

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

例如:

  • 如果用户写H,我想建议他:HTML
  • 如果用户写T,我想建议他:HTMLJavaScript
  • 如果用户写SQ,我想建议他:MySQLSQL
  • if the user writes H, I want to suggest him: HTML
  • if the user writes T, I want to suggest him: HTML, JavaScript
  • if the user writes SQ, I want to suggest him: MySQL, SQL

好吧,不使用jQuery UI就能做到吗?

Ok, is doing that possible without using jQuery UI?

推荐答案

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

an easy way to do this, is with Array.filter

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

you would need a polyfill to support IE browsers

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')

这篇关于如何为标签输入创建自动完成框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆