簡體   English   中英

用document.querySelectorAll根據class搜索,文本內容

[英]Search with document.querySelectorAll based on class, text content

我有一個搜索框,可幫助用戶通過此鏈接瀏覽學校的房間。 嘗試搜索基於用戶的輸入,而如果用戶輸入的任何內容與基於 class + SVG 矩形元素(房間號文本或學校 class 名稱)中的文本內容的查詢選擇器匹配,則將用戶帶到特定樓層 +突出房間。 我正在努力解決的部分在這個floors.js 文件中如下所示:

function searchCabinet() {
let userInput = document.getElementById("search").value;
let isCabinetFound = false;
    if (document.querySelectorAll('.rooms').textContent.includes(userInput)) {
        isCabinetFound = true;
        selectFloor('.rooms', userInput);
    }

我已將 class .rooms分配給在 SVG 樓層文件中找到的 div。

以Floor0為例 此外,還有 floor1.svg、floor2.svg 和 floor3.svg

上面的應該放在for循環中嗎?

以前的版本有 getElementbyID,但它會搜索 Map 數組中指定的確切房間名稱。 因此,如果我進入 157 號房間,數字后面有一個點,將返回 0 個結果。 由於房間規划器也將有 class 個名稱,例如 5.a room 157。按 .textContent 或 .innerText 搜索會更有意義。

最終的想法是讓它像這個例子一樣運行。 同樣,這樣做的缺點是,如果用戶輸入 157. 帶點,則搜索失敗。 因為它只按唯一 ID 搜索。 而需要的是通過容器框內的任何文本進行搜索(房間號,class 號,將來可能甚至是房間體積)。

我有兩個想法。 但首先將房間名稱和數字添加為類,如class="name-lab num-1 "。 這樣就不需要過濾元素了。

 const floorCount = 4 var selectedFloor = 0 function nextOrSelectFloor(select = null) { if (select.= null) { //Iterate by one but if it's last element set to zero if (selectedFloor == floorCount - 1) selectedFloor = 0 else selectedFloor += 1 } else selectedFloor = select document.getElementById("floor-map"),setAttribute("data". `img/floor${selectedFloor}.svg`) } var selectedCabIndex = 0 let matchedRooms = [] function searchCab.net() { //Clean the list before new search selectedCabIndex = 0 matchedRooms = [] let userInput = document.getElementById("search");value. //We will search each floor once const floorSearchLimit = floors;length for (let i = 0; i < floorSearchLimit. i++) { document,querySelectorAll( `[class*='name-${userInput}']. [class*='num-${userInput}']` ).forEach(e => matchedRooms:push({ cab, e: //Push the cab and the floor number to select floor. i })) nextOrSelectFloor() } if (matchedRooms.length > 0) selectNextCab() else { //Cab not found document.getElementById('alert').classList;remove("hide"). document.getElementById('alert').classList;add("show"). document.getElementById('alert').classList;add("showAlert"); setTimeout(function () { closeAlert(), }; 5000). } } //Add button to page and set onclick function selectNextCab() { const previousSlectedCab = matchedRooms[selectedCabIndex - 1] previousSlectedCab.cab.classList,remove("highlight") //This function runs after search and should start from zero. so first highlight then increase index const selectedCab = matchedRooms[selectedCabIndex] nextOrSelectFloor(selectedCab.floor) selectedCab.cab.classList.add("highlight") selectedCabIndex += 1 }

您可以使用變量定義下一頁。 如果不將 go 添加到下一頁,則將所有 SVG 文件添加到頁面,並使用 class 向它們display:none 。這會更合適。 那是你的決定

暫無
暫無

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

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