【发布时间】:2021-01-15 09:13:47
【问题描述】:
我在具有数据属性的 div 中有一个图像网格。我希望能够根据输入文本匹配通过 CSS 显示/隐藏它们。我循环遍历具有匹配类的 div 的数量,然后遍历输入数组中的单词,最后遍历数据属性字段中的单词。当我在两个内部数组文本值之间找到匹配项时,看起来 DOM 正在失去对外部索引的跟踪。控制台会看到三个循环索引值,但未调用 JavaScript show 命令。如果我对索引值 (0) 进行硬编码,则 show 命令确实有效。这感觉是一种非常混乱的方式。
HTML:
<img
src="images/game thumb 216px-1.png"
alt="Photo of hotline game"
class="gallery__photo photo1"
/>
</div>
<div
class="gallery__item"
data-new="true"
data-top="true"
data-value="2 neon jungle"
>
<img
src="images/game thumb 216px-2.png"
alt="Photo of neon jungle game"
class="gallery__photo photo2"
/>
</div>
JavaScript/jQuery:
//build object containing all gallery__item divs
//let galleryitems = document.getElementsByClassName("gallery__item");
//assign search input words to variable
let myInputWords = $("#search").val();
//create array of input words
let myInputWordsArray = myInputWords.split(" ");
//create array of gallery words
let myGalleryItemsArray = [];
for (let i = 0; i < galleryitems.length; i++) {
//fetch data-value attribute value
let myAttributeValue = galleryitems[i].getAttribute("data-value");
//add to gallery item array
myGalleryItemsArray.push(myAttributeValue);
}
//loop through input words array - outer
//loop through gallery words array - inner
let i, k, m = 0;
//loop through input element words array
for (i = 0; i < myInputWordsArray.length; i++) {
//loop through gallery items array
for ( k = 0; k < myGalleryItemsArray.length; k++) {
//loop through each gallery item which can contain multiple words and create a new array
let myGalleryItemArray = myGalleryItemsArray[k].split(" ");
//loop through each gallery item array element's words
for ( m = 0; m < myGalleryItemArray.length; m++) {
//console.log(myInputWordsArray[i]);
//console.log(myGalleryItemArray[m]);
//if the outer input array word matches the inner data word change the CSS display to block else set the CSS display to none
if (myInputWordsArray[i] === myGalleryItemArray[m]) {
galleryitems[k].style.display = "block";
//console.log(galleryitems[k]);
} else {
galleryitems[k].style.display = "none";
}
}
}
}
});
【问题讨论】:
标签: javascript html css