我正在尝试设置一个搜索,在一个html文件中提供多个搜索结果。假设html包含以下摘录:
<input id="search" type="text">
<div class="chapter" id="chap1">
<h1>Chapter 1 - Introduction</h1>
<p>Lorem Ipsum. Lorem Lorem Ipsum</p>
</div>
<div class="chapter" id="chap2">
<h1>Chapter 2 - Say hello</h1>
<p>Lorem Ipsum. Ipsum Lorem Ipsum</p>
</div>
<div class="chapter" id="chap3">
<h1>Chapter 3 - Say bye</h1>
<p>Ipsum Ipsum. Ipsum Ipsum Ipsum</p>
</div>
如果我现在要搜索"Lorem",我想为类"chapter"中包含"Lorem"的每个div得到一个结果(=第一个和第二个div=2个搜索结果)。每个搜索结果都应该只是一个链接,其内容为h1,并在单击时指向相应的div。
示例:
<p>Your search has returned 2 results.</p>
<a>Chapter 1 - Introduction</a>
<a>Chapter 2 - Say hello</a>
理想情况下,在我删除搜索文本或点击其中一个结果之前,不应该显示原始内容。
非常感谢!非常感谢你的帮助!
像这样?:https://jsfiddle.net/878dkrd9/
$(function(){
$('#search').keyup(function(){
var searchText = $('input#search').val();
if(searchText.length > 0){
$('div.chapter:contains(' + searchText + ')').show();
$('div.chapter:not(:contains(' + searchText + '))').hide();
}else{
$('div.chapter').show();
}
});
// Required to make the jQuery contains NON-Case-sensitive
jQuery.expr[':'].Contains = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
// OVERWRITES old selecor
jQuery.expr[':'].contains = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
});
经过几次尝试,我现在已经完全得到了我想要的东西(尽管代码可能不是100%写得好)。:)
谢谢你,格雷格!
这是最终结果的链接:
$(function(){
$('#search').keyup(function(){
var searchText = $('input#search').val();
if(searchText.length > 0){
$('div.chapter:contains(' + searchText + ')').show();
$('div.chapter:not(:contains(' + searchText + '))').hide();
$('p.weg').hide();
$('a').addClass("blue");
$('pre').addClass("show");
}else{
$('div.chapter').show();
$('p.weg').show();
$('a').removeClass("blue");
$('pre').removeClass("show");
}
});
https://jsfiddle.net/878dkrd9/106/