亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從 span 中獲取每個值并使用 js 或 jquery 將所有值設置為變量?

如何從 span 中獲取每個值并使用 js 或 jquery 將所有值設置為變量?

qq_遁去的一_1 2023-06-09 14:44:54
我想在添加任何單詞之前將標簽列表檢查到 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('');}     }  }})
查看完整描述

1 回答

?
慕碼人8056858

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>


查看完整回答
反對 回復 2023-06-09
  • 1 回答
  • 0 關注
  • 194 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號