1 回答

TA貢獻1803條經驗 獲得超6個贊
每次用戶釋放一個鍵時,您都會查看它,然后如果它是終止字符(您選擇了小于號/左尖括號),您將獲得他們輸入的整個字符串,減去終止字符。
到目前為止,一切都很好。
事情有點不對勁的地方在你的循環中。您正在遍歷每個現有的迷你標簽 span 元素,但您正在根據用戶輸入的值測試整個元素。您需要僅針對第一個文本節點進行測試,否則您將永遠無法獲得匹配項。
另外,當沒有迷你標簽元素時,一開始會發生什么?長度將為 0,所以你永遠不會進入循環——你永遠不會開始。
我們能做的是記住我們是否有匹配項,在有匹配項時跳出循環,如果沒有匹配項則附加迷你標簽 span。
查看此代碼段和代碼中的注釋。
順便說一句,要注意的一件事是,如果您的用戶在您的輸入元素中鍵入了一些討厭的代碼,您將其放入 DOM 中,這可能很危險。由于您正在談論標簽,因此您可能希望丟棄所有非字母數字字符,但這取決于您的用例。
$('.addTag').on('keyup',function(e){
var inputTag = e.keyCode || e.which;
if (inputTag === 188) {
var spanValues = document.getElementsByClassName('mini-tag');
var thisValue = $(this).val().slice(0,-1);
console.log(spanValues)
//We just want to see if we have got a match
//We havent got one yet so let's remember that
let gotMatch = false;
//then go through testing the latest tag input against all those we already have to see if there is a match
for(i=0;i<spanValues.length;i++){
if(thisValue === spanValues[i].firstChild.nodeValue){
gotMatch = true;
break; //once we've got a match we know we don't want to carry on looking through the existing tags so get out of the for loop
}
}
//now we have been through all the exising tags
//we append a span element with the tag (and some fancy fontawesome)into the tags div
if (!gotMatch) {
$('.tags').append("<span class='mini-tag'>" + thisValue +
"<i class='fas fa-times fa-xs'></i>" + " " + "</span>");
}
$(this).val(''); //and whether we got a match or not we want to clear the input element so the user can type in another tag
}})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="addTag" type="text"/>
<div class="tags"></div>
添加回答
舉報