如何从 span 中获取每个值并使用 js 或 jquery 将所有值设置为变量?

我想在添加任何单词之前将标签列表检查到 div 中,以免通过 jquery 重复任何单词


$('.addTag').on('keyup',function(e){

var inputTag = e.keyCode || e.which;

var spanValues = document.getElementsByClassName('mini-tag');

var thisValue = $(this).val().slice(0,-1);

console.log(spanValues)

if(inputTag === 188){

  for(i=0;i<spanValues.length;i++){

    if(thisValue === spanValues[i]){

      $('.addTag').val('')

    }else{

      $('.tags').append("<span class='mini-tag'>" +  thisValue + 

       "<i class='fas fa-times fa-xs'></i>" + " "  + "</span>");

      $(this).val('');} 

    }

  }

})


qq_遁去的一_1
浏览 161回答 1
1回答

慕码人8056858

每次用户释放一个键时,您都会查看它,然后如果它是终止字符(您选择了小于号/左尖括号),您将获得他们输入的整个字符串,减去终止字符。到目前为止,一切都很好。事情有点不对劲的地方在你的循环中。您正在遍历每个现有的迷你标签 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 thatlet gotMatch = false;//then go through testing the latest tag input against all those we already have to see if there is a match&nbsp; for(i=0;i<spanValues.length;i++){&nbsp; &nbsp; if(thisValue === spanValues[i].firstChild.nodeValue){&nbsp; &nbsp; &nbsp;gotMatch = true;&nbsp; &nbsp; &nbsp;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&nbsp; &nbsp; }&nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; //now we have been through all the exising tags&nbsp; &nbsp; //we append a span element with the tag (and some fancy fontawesome)into the tags div&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if (!gotMatch) {&nbsp; &nbsp; &nbsp; $('.tags').append("<span class='mini-tag'>" +&nbsp; thisValue +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;"<i class='fas fa-times fa-xs'></i>" + " "&nbsp; + "</span>");&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; $(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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript