使用javascript从html列表中筛选元素

Filtering elements out of a html list using javascript

本文关键字:筛选 元素 列表 html javascript 使用      更新时间:2023-09-26

所以我有一个项目列表和一个文本框,我想将隐藏属性应用于与文本框中不匹配的项目。我正在使用javascript在浏览器上实时执行此操作。这是我的HTML(不用担心g:textbox,我是在grails中完成的)

Filter List :<g:textBox id = filter onkeyup = Javascript:filter()>
<ul id = 'terms'>
    <li id = 'AFUE'>AFUE
        <p> Annualized Fuel Utilization Efficiency is a measure of your furnace’s heating efficiency. The higher the AFUE percentage, the more efficient the furnace. The minimum percentage established by the DOE for furnaces is 78.</p>
    </li>
    <li id = 'Airflow'>Airflow
        <p> The distribution or movement of air. </p>
    </li>
    <li id = 'Air Handler/Coil Blower'>Air Handler/Coil Blower
        <p> The indoor part of an air conditioner or heat pump that moves cooled or heated air throughout the ductwork of your home. An air handler is usually a furnace or a blower coil.</p>
    </li>
    <li id = 'Bioaerosols'>Bioaerosols
        <p>Microscopic living organisms that grow and multiply in warm, humid places.</p>
    </li>
</ul>

所以我有了html设置,现在我需要编写javascript
1.我不确定我是否正确使用了filter.text和2.不确定如何到达ul id 内的li id

function filter(){
   // on each li item in ul where ul id = 'terms'
   {
      if //li item id.match(${filter.text})
      {
           //li item.hidden = "false"
      }
      else if !//li item id.match(${filter.text})
      {
           //li item.hidden = "true"
      }
      else if ${filter.text} = ""
      {
           //set all items hidden = "false"
      }
   }
}

我想说的是,我需要对一组元素进行迭代,但这可能只是我

中的ruby/cucumber
var filterText = document.getElementById('filter').value,
    lis = document.querySelectorAll('#terms li'),
    x;
for (x = 0; x < lis.length; x++) {
    if (filterText === '' || lis[x].innerHTML.indexOf(filterText) > -1) {
        lis[x].removeAttribute('hidden');
    }
    else {
        lis[x].setAttribute('hidden', true);
    }
}

http://jsfiddle.net/ExplosionPIlls/bWRkz/

以下是一种在纯javascript:中搜索<li> id值的方法

function keyTyped(e) {
    var items = document.getElementById("terms").getElementsByTagName("li");
    var matches = [];
    var typed = e.target.value;
    var text, i;
    for (i = 0; i < items.length; i++) {
        text = items[i].id;
        if (!typed || text.indexOf(typed) != -1) {
            matches.push(items[i]);
        }
    }
    // now hide all li tags and show all matches
    for (i = 0; i < items.length; i++) {
        items[i].style.display = "none";
    }
    // now show all matches
    for (i = 0; i < matches.length; i++) {
        matches[i].style.display = "";
    }
}

演示:http://jsfiddle.net/jfriend00/wFEJ5/

这个演示实际上隐藏了元素,这样你就可以在演示中直观地看到它们。如果这是您最终想要的结果,那么您显然可以更改代码以添加/删除隐藏的属性。