我有这段代码,我想查找重复项 如果发现我想要警告它已经存在,所以用户无法插入该单词/标签。可以请一些人帮忙
<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>
答案 0 :(得分:0)
您可以拥有添加标签的地图,在添加标签之前,请检查它是否存在:
$(function() { // DOM ready
// ::: TAGS BOX
// added tags (mark 'a' and 'b' as already added)
let tags = {
'a': true,
'b': true
};
$("#tags input").on({
focusout: function() {
var txt = this.value.replace(/[^a-z0-9\+\-\.\#]/ig, ''); // allowed characters
if (txt) {
if (tags[txt]) { // if the tag already exists show an error
console.log(txt + ' already exists');
} else {
$("<span/>", {
text: txt.toLowerCase(),
insertBefore: this
});
tags[txt] = true; // add the tag
}
}
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();
var text = $(this).text();
tags[text] = false; // remove the tag
}
$('#tags input').prop('disabled', false);
});
});
&#13;
#tags {
float: left;
border: 1px solid #ccc;
padding: 5px;
font-family: Arial;
}
#tags>span {
cursor: pointer;
display: block;
float: left;
color: #fff;
background: #789;
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 {
background: #eee;
border: 0;
margin: 4px;
padding: 7px;
width: auto;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="search-container">
<div id="tags">
<span>a</span> <span>b</span>
<input type="text" value="" class="paste" id="search" placeholder="Add a tag" />
</div>
</div>
&#13;