隐藏列表项而不失去顺序

3
有没有可能隐藏<ol>中特定的<li>而不改变每个列表项前面的数字?我正在尝试制作一个搜索功能,该功能仅显示与用户输入匹配的<li>。但是,如果要隐藏第二个<li>,它将更改第三个<li>前面的数字为2,但它应该保持为3。
如果可能的话,我希望得到一种无需使用jQuery(Prototype可以)的答案。但如果没有jQuery,则可以使用jQuery。
HTML:
<label>Search: <input type="text" id="search"/></label> 
<button id="clear">Clear</button>

<div id="list">
    <ol>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
    </ol>
</div>

Javascript:

window.onload = function(){
    document.getElementById("search").onkeyup = updateList;
    document.getElementById("clear").click = clearInput;
}

function updateList(){
    var list = document.getElementById("list");
    var listitems = list.getElementsByTagName("li");
    for(var i = 0; i < listitems.length; i++) {
        var current = listitems[i].innerHTML.toLowerCase();
        if(current.indexOf(document.getElementById("search").value.toLowerCase()) != -1) {
            listitems[i].style.display = "list-item";
        } else {
            listitems[i].style.display = "none";
        }
    }   
}

function clearInput(){
    document.getElementById("search").value = "";
    updateList();
}
3个回答

1
如果我想隐藏项目并使其在视觉上消失,而不使用display:none,我会更改项目的类名:
var value = document.getElementById("search").value.toLowerCase();
if (value && current.indexOf(value) != -1) {
    listitems[i].className = "hidden";
} else {
    listitems[i].className = "";
}

CSS

.hidden {
    position: absolute;
    top: -1000px;
    left: -1000px;
}

另外我稍微修改了你的代码:在显示/隐藏项目之前,需要检查搜索词是否为空。

示例:http://jsfiddle.net/43PcY/2/


感谢您提供的解决方案。然而,在这种情况下,不需要检查值。如果用户完全删除输入或单击“清除”按钮,则应更新列表。 - Emiel

1

http://jsfiddle.net/CYs46/

可见性 + 高度 ;-)

稍微改变了您的代码,像fiddle一样

    if(current.indexOf(document.getElementById("search").value.toLowerCase()) != -1) {
        listitems[i].style.visibility = "visible";
        listitems[i].style.height = "auto";
    } else {
        listitems[i].style.visibility = "hidden";
        listitems[i].style.height = "0px";
    }

0

将可见性设置为隐藏,并将高度设置为零(仅设置高度也可能有效):

document.getElementById('hideme').style.visibility = 'hidden';
document.getElementById('hideme').style.height = '0px';
document.getElementById('button').onclick = function() {
    document.getElementById('hideme').style.visibility = '';
    document.getElementById('hideme').style.height = '';
};

JSFiddle

编辑:不使用jQuery


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接