JS中的搜索帖子字段

问题描述 投票:0回答:1

我有一个带帖子的博客。我创建了一个搜索字段,当您开始在其中撰写帖子标题时,在我的博客上您将收到该帖子。他们其余的都有展示块。我的帖子包括图片,标题和简短说明。

HTML

.main_content
   .titlePictures
       .blog_img
          img
       .textContent
          .title
             h2 
               a Title
          .allTxt

因此,我用纯JS准备了一个函数,该函数可以处理此搜索字段。而且有效,buuuuut ..我只有该帖子的标题,没有图片也没有描述。而且我的函数有很多循环,我认为不合适:(我该如何更改]

https://codepen.io/aniaska4/pen/gOOBjwy

   document.querySelector(".search input").addEventListener("keyup", function() {
    let input = document.querySelector(".search input");
    console.log(input);
    const filter = input.value.toUpperCase();
    const title = document.querySelectorAll(".blog .articles .title h2");
      for (let i = 0; i < title.length; i++) {
      let a = title[i].getElementsByTagName("a")[0];
      let txtValue = a.textContent || a.innerText;
      const pic = document.querySelectorAll(".titlePictures img");
       for (let y = 0; y < pic.length; y++) {
        const txt = document.querySelectorAll(".allTxt");
         for (let x = 0; x < txt.length; x++) {
           if (txtValue.toUpperCase().indexOf(filter) > -1) {
           title[i].style.display = "block";
           txt[x].style.display = "block";
           pic[y].style.display = "block";
           } else {
            title[i].style.display = "none";
            txt[x].style.display = "none";
            pic[y].style.display = "none";
          }
        }
     }
  }
});
javascript loops search
1个回答
0
投票

您可以使用str.search方法

这里是codepen,可以解决您的问题。

我已经添加了理解代码所需的所有注释,如果您需要任何澄清,请告诉我。

document.querySelector(".search input").addEventListener("keyup", function() {
  let input = document.querySelector(".search input");
  const filter = input.value.toLowerCase();

  // Select all posts
  const posts = document.querySelectorAll(".main_content");

  // Loop on all the posts
  for(post of posts) {
    // Select the title of the post
    let title = post.querySelector('.title h2 a');

    // Search title text by filter
    let found = title.innerText.toLowerCase().search(filter);

    // If found === -1 hide the post, otherwise show it
    post.style.display = found === -1 ? "none" : "block";
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.