嘿,我正在尝试创建一个搜索字段,根据用户键入的内容过滤或显示/隐藏(最好)列表元素,然后单击搜索按钮.我不知道该怎么做.我尝试过的所有东西都不能用,并且我不确定最好的方法,比如我使用show和hide还是有更好的东西?
这是我的HTML:
<html>
<head>
</head>
<body>
<label for="filter">Filter</label>
<input type="text" name="filter" value="" id="filter" />
<a id="addtag" href="#">Search</a>
<ul>
<li id="Hero1">Superman</li>
<li id="Hero2">Batman</li>
<li id="Hero3">Spiderman</li>
<li id="Hero4">Iron Man</li>
<li id="Hero5">The Hulk</li>
</ul>
</body>
</html>
因此,如果有人输入“超人”并单击搜索按钮,则只会显示超人列表元素.
对此的任何帮助都会很棒.谢谢.
解决方法
这使用jQuery并创建滑动动画.
这将是HTML:
这将是HTML:
<div id="wrap">
<h1 id="header">List of countries</h1>
<ul id="list">
<li><a href="#">List Item</a></li>
<li><a href="#">Add Unlimited Items</a></li>
</ul>
</div>
JavaScript的
(function ($) {
// custom css expression for a case-insensitive contains()
jQuery.expr[':'].Contains = function(a,i,m){
return (a.textContent || a.innerText || "").toupperCase().indexOf(m[3].toupperCase())>=0;
};
function listFilter(header,list) { // header is any element,list is an unordered list
// create and add the filter form to the header
var form = $("<form>").attr({"class":"filterform","action":"#"}),input = $("<input>").attr({"class":"filterinput","type":"text"});
$(form).append(input).appendTo(header);
$(input)
.change( function () {
var filter = $(this).val();
if(filter) {
// this finds all links in a list that contain the input,// and hide the ones not containing the input while showing the ones that do
$(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
$(list).find("a:Contains(" + filter + ")").parent().slideDown();
} else {
$(list).find("li").slideDown();
}
return false;
})
.keyup( function () {
// fire the above change event after every letter
$(this).change();
});
}
//ondomready
$(function () {
listFilter($("#header"),$("#list"));
});
}(jQuery));
CSS是可选的.
JSfiddle演示:http://jsfiddle.net/4feug/