javascript - 如何在博客页面中获取搜索栏以搜索选择性文章?

标签 javascript html css

我正在为我的健身网站工作,我制作了一个博客页面,现在有很多文章可用,我制作了一个加载更多按钮来显示更多文章,脚本工作正常,接下来我想放一个页面顶部的搜索栏,以便用户可以在搜索栏中看到他写的文章。我做了一个脚本我不知道问题在哪里

代码如下

现在的 html 代码是:

<input type="text" id="inputarticle" onkeyup="myfunction()" size="162" placeholder="Enter the article name">

<div class="grid-container">
<div class="grid-hidden1">
            <img class="blog-cl-1-image">
            <h2 > <a href="fat.html">Importance of Fat for human Body</a> </h2>
            <h4>August 21 2019</h4>
            <p>When you eat fat in your diet the most important  thing that matters are the type of fat you eat. New research shows that healthy fats are important for optimal health.</p>
        </div>
        <div class="grid-hidden1">
            <img class="blog-cl-2-image">
            <h2> <a href="zinc.html">Role of Zinc in Human Body</a> </h2>
            <h4>August 21 2019</h4>
            <p>Zinc is an essential nutrient that plays an important role in the human body. As your body doesn’t produce zinc so it is essential to take it from food or supplements.</p>
        </div>
</div>

现在的 javascript 是:-

function myfunction() {
  // Declare variables
  var input, filter, ul, h2, a,i, txtValue;
  input = document.getElementById("inputarticle");
  filter = input.value.toUpperCase();
  ul = document.getElementsByClassName("grid-container");
  h2 = ul.getElementsByTagName("h2");

  // Loop through all list items, and hide those who don't match the search query
  for (i = 0; i < li.length; i++) {
    a = h2[i].getElementsByTagName("a")[0];
    txtValue = a.textContent || a.innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      h2[i].style.display = "";
    } else {
      h2[i].style.display = "none";
    }
  }
}

不知道问题出在哪里?请帮忙

最佳答案

尝试更改 for 循环 if 语句中的以下行,看看它是否有效:

h2[i].style.display = "";

h2[i].style.display = "block";

如果没有完整的 HTML 文件和逻辑,很难确切知道发生了什么。另外,不确定这是否是错字,但您的 HTML 缺少第一个示例元素的开头。

<div class="grid-hidden1">
        <img class="blog-cl-1-image">
        <h2 > <a href="fat.html">Importance of Fat for human Body</a> </h2>
        <h4>August 21 2019</h4>
        <p>When you eat fat in your diet the most important  thing that matters are the type of fat you eat. New research shows that healthy fats are important for optimal health.</p>
    **</div>** <-- MISSING OPENING DIV
    ...

希望这对您有所帮助!

关于javascript - 如何在博客页面中获取搜索栏以搜索选择性文章?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57730349/

相关文章:

html - 修复了居中博文旁边的侧边栏

javascript - 基本构造函数对象帮助 - JS

javascript - JavaScript 压缩库使用什么技术来最小化文件大小?

javascript - AngularJS-如何实现Angular中的点击

javascript - rails 5 : hide navigation drop-down on click

html - 最高级别第一个标题的CSS选择器?

javascript - Angular 4 : Scroll to top of page programmatically

javascript - 使用对象在 html 中创建列表

html - CSS 在数据单元格上方显示表格行标题

html - 如何用 CSS 放置 3 个色 block HTML