0

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

我想说我需要遍历一组元素,但这可能是我身上的红宝石/黄瓜

4

2 回答 2

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/

于 2013-02-16T18:38:20.387 回答
1

这是一种<li>在纯 javascript 中搜索 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/

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

于 2013-02-16T18:45:39.687 回答