【发布时间】:2017-06-22 09:54:36
【问题描述】:
我有这段代码,我想查找重复项 如果发现我想提醒它已经存在,所以用户不能插入那个词/标签。有人可以帮忙吗
<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>
【问题讨论】:
-
用
.each()遍历span,测试是否$(this).text() == txt。 -
if(/(188|13|32)/.test(ev.which))应该是if(/^(188|13|32)$/.test(ev.which))。您需要锚点,否则它将匹配130和132之类的内容。
标签: javascript jquery html