隐藏没有指定字符串的<div> </div>

时间:2012-12-07 00:57:34

标签: javascript css search html

所以,尽可能简单地把它放进去...... 我有多个包含文本的div,如下所示:

<div id=1 style="position:relative"><font color=color>Hello Hello</font></div>
<div id=2 style="position:relative"><font color=color>Hello Goodbye</font></div>
<div id=3 style="position:relative"><font color=color>Goodbye Goodbye</font></div>

我想在我的页面上有一个搜索框,我可以输入字符串,例如:“Hello”隐藏最后一个div,“Hello Hello”隐藏最后两个div,“Hello Goodbye”隐藏第一个最后,“Goodbye Goodbye”隐藏了前两个div。输入不必具有案例敏感性,但我更喜欢输入字符串的顺序。

提前致谢! -Starletts

PS:如果可能的话,我宁愿不要使用JQuery。

2 个答案:

答案 0 :(得分:1)

在纯 W3C规范中:

var forEach = Array.prototype.forEach;    

document.getElementById('inputID').addEventListener('keyup', function( event ) {
    forEach.call(document.querySelectorAll('div'), function( div ) {
        if( div.textContent.split(/\s+/).indexOf( event.target.value ) > -1 ) {
            div.style.display = 'none';
        } else {
            div.style.display = 'block';
        }
    });
}, false);

演示:http://jsfiddle.net/FA2nj/

答案 1 :(得分:1)

HTML:

<input type="text" id="my_input">

使用Javascript:

document.getElementById('my_input').addEventListener('keyup', function () {
    var search_for = this.value;
    var divs = document.getElementsByTagName('div');
    Array.prototype.forEach.call(divs, function (div) {
       if (search_for && div.textContent.toLowerCase().indexOf(search_for.toLowerCase()) > -1) {
           div.style.display = 'none'; // to hide
       }
       else {
           div.style.display = 'block';
       }
    });
});​