繁体   English   中英

如何为标签输入创建自动完成框?

[英]How can I create an autocomplete box for the tag input?

这是我的代码:

 $(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> 

如您所见,我正在尝试为帖子创建标签附件框。 现在,我需要为标签创建一个自动完成框。 我可以通过jQuery UI来做到这一点,但我不想这么做。 因为仅将jQuery UI用于自动完成功能似乎负担不起。

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

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

例如:

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

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

尝试这个:

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

一个简单的方法是使用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')

暂无
暂无

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

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