嘿,我正在尝试创建一个搜索字段,根据用户键入的内容过滤或显示/隐藏(最好)列表元素,然后单击搜索按钮。我不知道该怎么做。我尝试过的所有东西都不起作用,并且我不确定最好的方法,比如我使用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>
因此,如果有人输入“超人”并点击搜索按钮,则只会显示超人列表元素。
对此的任何帮助都会很棒。感谢。
答案 0 :(得分:4)
这也使用jQuery并创建一个滑动动画。 这将是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/
答案 1 :(得分:3)
使用jQuery搜索插件like this one.
可能会更好答案 2 :(得分:3)
非常基本的版本,但不需要插件,它可以工作:
$("#addtag").click(function(){
$("ul li").hide()
.filter(":contains('"+ $("#filter").val() +"')").show()
return false;
})
答案 3 :(得分:2)
对duckyflip的答案略有改进,使搜索不区分大小写:
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
$("#addtag").click(function(){
$("ul li").hide()
.filter(":contains('"+ $("#filter").val() +"')").show()
return false;
});