【发布时间】: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,我想建议他:HTML,JavaScript - 如果用户写
SQ,我想建议他:MySQL,SQL
好的,不使用 jQuery UI 是否可以做到这一点?
【问题讨论】:
-
根据您的专业水平,我认为这对您来说是不可能的。下面的解决方案定义了一个函数自动完成。这将返回一个匹配标签的数组。在您的示例中,您将在
keyup事件上调用此函数并显示从该函数返回的结果。
标签: javascript jquery html css