使用javascript过滤html列表中的元素

时间:2013-02-16 18:10:15

标签: javascript list

所以我有一个项目列表和一个文本框,我想将隐藏属性应用于与文本框中的内容不匹配的项目。我正在使用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  我不确定我是否正确使用了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"
      }
   }
}

我想说我需要迭代一系列元素,但这可能就是我的红宝石/黄瓜

2 个答案:

答案 0 :(得分:2)

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/

答案 1 :(得分:0)

这是一种在普通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/

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