【发布时间】:2020-02-27 20:59:54
【问题描述】:
我正在尝试使用 jQuery 构建搜索过滤器。首先,我使用$(list).find('p').hide(); 隐藏了 html 的所有内容。
我想要做的是当用户在文本框中输入文本时,它应该在 html 中找到该词,如果找到它应该在 its<div> 中显示整个内容。我不知道我做错了什么?
这里是JSFiddle
<!DOCTYPE html>
<html>
<head>
<title>Some Title</title>
<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script>
(function ($) {
jQuery.expr[':'].Contains = function(a,i,m){
return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
function listFilter(header, list) {
$(list).find('p').hide();
var form = $("<form>").attr({"class":"filterform","action":"#"}),
input = $("<input>").attr({"class":"filterinput","type":"text"}),
search = $("<input>").attr({"class":"filterbutton","type":"button","name":"btn1","value":"Search"});
$(form).append(input).appendTo(header);
$(input)
.change( function () {
var filter = $(this).val();
if(filter) {
$(list).find("p:contains("+filter+")").closest("div").show();
} else {
$(list).find('p').hide();
}
return false;
})
.keyup( function () {
$(this).change();
});
}
$(document).ready(function () {
listFilter($("#header"), $("#list"));
});
}(jQuery));
</script>
</head>
<body>
<h1 id="header">Collection</h1>
<div id="list">
<div id='p1'>
<p>First Paragraph</p>
<p>Abbot and Costello - Africa Screams</p>
</div>
<div id='p2'>
<p>Second Paragraph</p>
<p>Abbot and Costello - Frank/Meet</p>
</div>
<div id='p3'>
<p>Third Paragraph</p>
<p>addin</p>
</div>
<div id='p4'>
<p>Forth Paragraph</p>
<p>Begins</p>
</div>
</div>
</body>
</html>
显然我想使用按钮单击而不是文本更改事件来实现这一点。我正在尝试动态创建按钮
search = $("<input>").attr({"class":"filterbutton","type":"button","name":"btn1","value":"Search"});
【问题讨论】: