javascript - 如何使搜索列表更短?

标签 javascript html css

t short

如何让搜索结果显示的更短,比如4行,而不是全部显示到底部?

这是我的代码:

    li = ul.getElementsByTagName("li");
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];

CSS 代码:

#myUL li a {
  transform: translate(270px,-1400px); 
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  width: 28%;
  padding: 12px;
  text-decoration: none;
  font-size: 16px;
  color: black;
  display: block;
}

其余代码:

var UL = document.getElementById("myUL");
// hilde the list by default
UL.style.display = "none";
var searchBox = document.getElementById("myInput");

// show the list when the input receive focus
searchBox.addEventListener("focus",  function(){
    // UL.style.display = "block";
});

// hide the list when the input receive focus
searchBox.addEventListener("blur", function(){

});


function myFunction() {
    var input, filter, ul, li, a, i;
    input = document.getElementById("myInput");
    ul = document.getElementById("myUL");
    filter = input.value.toUpperCase();
    // if the input is empty hide the list
    if(filter.trim().length < 1) {
        ul.style.display = "none";
        return false;
    } else {
        ul.style.display = "block";
    }
    li = ul.getElementsByTagName("li");   
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];

        // This is when you want to find words that contain the search string
     if (a.innerHTML.toUpperCase().indexOf(filter) > -1) { 
        li[i].style.display = "";
     } else {
        li[i].style.display = "none";
    } 

请帮助我,我现在正在努力解决这个问题 :( 提前致谢!

最佳答案

试试这个

var limit = 4;    
for (i = 0, j = 0; i < li.length && j < limit; i++) {

在匹配的 block 中,这个

// This is when you want to find words that contain the search string
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
    li[i].style.display = "";
    j++;
} else {

当你进行了 4 次匹配后,循环将终止

关于javascript - 如何使搜索列表更短?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58231769/

相关文章:

javascript - 如何从输入值中进行多项选择?

javascript - 从 XML 中提取数据不起作用

javascript - 从 url 获取数据并放在网站上

javascript - 如何防止 Unicode 字符从 JavaScript 呈现为 HTML 中的表情符号?

javascript - 意外的 ionicons 行为

javascript - 如何在多个 Canvas html5上绘制圆圈?

html - 仅CSS的砌体布局

javascript - REGEX - 对于字母数字/数字,其间可能有斜线

javascript - jQuery 迭代嵌套 html 列表

使用 webkitGetAsEntry 的 Javascript 拖放文件上传问题