2011-05-27 32 views
1

问候,搜索李名单与jQuery

我有一大堆的DIV中<li>项目,股利是滚动

我想有一个文本框标记包含特定文本的第一立从文本框和搜索按钮。

和李应显形:(

我不知道如何做到这一点:(

+2

我没有任何线索,你想要什么:( – 2011-05-27 15:01:30

+0

我想你想的东西像jQuery UI自动完成实施?http://jqueryui.com/demos/autocomplete/ – superUntitled 2011-05-27 15:08:00

+0

@Pedro Correia:我想突出显示一个li,其中包含我放在搜索文本框中的文本 @superUntitled:这已经很好帮助了,但仍然需要突出显示LI并滚动div直到出现:S – Killercode 2011-05-27 15:08:23

回答

4

Live Demo Updated with scrolling

标记

<div id='test'> 
    <ul> 
     <li>Text</li> 
     <li>Something</li> 
     <li>Hey</li> 
     <li>der</li> 
     <li>herp</li> 
     <li>derp</li> 
     <li>Testing</li> 
    </ul> 
</div> 

JS

$('#searchBtn').click(function(){ 
    var searchString = $('#searchText').val(), 
     foundLi = $('li:contains("' + searchString + '")'); 

    foundLi.addClass('found'); 
    $('#test').animate({ scrollTop: foundLi.offset().top}); 
}); 
+0

请注意,如果搜索字符串包含某些字符 – Lepidosteus 2011-05-27 15:14:04

+0

对不起,无法正常工作,则使用该方式的“包含”选择器会中断.... – Killercode 2011-05-27 15:49:56

+0

发现问题:P – Killercode 2011-05-27 15:51:35

0

的HTML:

<div style="height: 40px; overflow-y: scroll" id="my_div"> 
    <li>the first li</li> 
    <li>the second li</li> 
    <li>the third li</li> 
    <li>the fourth li</li> 
    ... 
</div> 

<input type="text" id="my_text_box" /> 
<input type="submit" id="my_search_button" /> 

的JavaScript:

$('#my_search_button').click(function(e) { 
    var my_search = $('#my_text_box').val(); // the text to search for 
    var $my_div = $('#my_div'); // the div 
    $my_div.find('li').each(function(idx, elem) { 
     $elem = $(elem); 
     if ($elem.text().indexOf(my_search) != -1) { // if it contains your searched text 
     $elem.show(); // display it ? only if needed, unclear from question 
     $elem.addClass('highlighted'); // add your class for the highlight 
     $my_div.scrollTop($elem.position().top); // scroll to it 
     return false; // stop the loop 
     } 
    }); 

    e.preventDefault(); // stop an actual form from being submitted 
}); 
0

我期待对于s类似的东西:

我的网站的访问者应该能够在可点击的位置列表中进行搜索(对于本地天气报告)。

理想的情况下,应该有一个匹配的机制:

的游客开始进入位置的名称,该名称应自动在搜索领域建议。

有没有这样的代码?