簡體   English   中英

想要使用 JavaScript 過濾項目列表(li)以獲得部分匹配而不是精確(短語)匹配

[英]Want to Filter a list of items(li) for a partial match rather than exact(phrase) match using JavaScript

考慮以下功能:

//This piece of code works for exact word match but I want something more of a partial match.
    function filterItems(ev) {
        let text = ev.target.value.toLowerCase();
        let items = item_list.getElmentsByTagName("li");
        Array.from(items).forEach(item => {
         let item_name = item.firstChild.textContent;
         if(item_name.toLowerCase().indexOf(text) !== -1) {
            item.style.display = "block";
         } else {
            item.style.display = "none";
         }
      })
    }

這是我正在嘗試做的事情,例如在搜索詞組本身上使用過濾器

function filterItems(ev) {
     let text = ev.target.value.toLowerCase();
     let items = item_list.getElmentsByTagName("li");
     Array.from(items).forEach(item => {
        let item_name = item.firstChild.textContent;
        if(item_name.toLowerCase().split("").filter(ch => ch.indexOf(text) !== -1)) {
                item.style.display = "block";
             } else {
                item.style.display = "none";
             }
          })
        }

它是否接近我想要做的事情,它似乎沒有響應瀏覽器上的這段代碼!!

從您的最后一條評論來看,我相信這實現了您所追求的行為。 我的this.target是你的text變量。 您可以在 forEach 項目循環中調用以下doesFilterMatchTarget()

我添加了內聯注釋以供進一步解釋。

  function doesFilterMatchTarget(filter) {
    filter = filter.toLowerCase();

    if (filter.length === -1) { //empty state should not match
      return false;
    }

    let currentTarget = this.target; //initialise to your starting target e.g. 'list 01'

    for (let i = 0; i < filter.length; i++) {
      //call our helper function below to check and update our target word
      currentTarget = this.updateTargetWord(currentTarget, filter[i]);
      if (currentTarget === null) {
        return false;
      }
    }

    return true; //we have looped through every letter and they were all found in a correct location
  }


  function updateTargetWord(currentTarget, letterToSearchFor) {
    let index = currentTarget.search(letterToSearchFor);
    if (index === -1) {
      return null; //the letter was not in the target
    }

    // then we want to return the remainder of this target string from the next character to the end of the string
    return currentTarget.substring(index + 1, currentTarget.length);
  }

注意:這可能可以優化,但它似乎返回了您正在尋找的內容。

您可以在這里使用帶有 i 標志的正則表達式,它將忽略大小寫,在這里我們使用構造函數使用動態正則表達式。

function filterItems(ev) {
 const regExp = new RegExp(`[${ev.target.value}]`, 'i');
 let items = item_list.getElmentsByTagName("li");
 Array.from(items).forEach(item => {
    let item_name = item.firstChild.textContent;
    if(regExp.test(item_name)) {
            item.style.display = "block";
         } else {
            item.style.display = "none";
         }
      })
    }

如果要在搜索框為空時顯示所有項目,則應該是

      function filterItems(ev) {
    // using regex
    let regExp = new RegExp(`[${ev.target.value}]`, 'i');
    // converting text to lowerCase
    // let text = ev.target.value.toLowerCase();
    // get ul li elemnts
    let items = item_list.getElementsByTagName("li");
    // Convert it to an array
    Array.from(items).forEach(item => {
      let item_name = item.firstChild.textContent;
      if (!ev.target.value || regExp.test(item_name)) {
        item.style.display = "inline-block";
      } else {
        item.style.display = "none";
      }
    });
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM