【问题标题】:Multiple search results from a search within a single file在单个文件中搜索的多个搜索结果
【发布时间】:2016-02-06 22:54:23
【问题描述】:

我正在尝试设置一个搜索,该搜索在单个 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”,我想获得包含“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>

理想情况下,在我删除搜索文本或单击其中一个结果之前,不应显示原始内容。

非常感谢!非常感谢您的帮助!

【问题讨论】:

  • 在您的 javascript 函数中创建链接,该链接具有 href="#chap1"(或您想要与之关联的任何其他 ID)。我建议为此使用 jQuery,因为您可以使用 CSS 选择器轻松导航。 beski.wordpress.com/2009/04/21/…
  • 示例输出中的链接在哪里?

标签: php jquery sql search


【解决方案1】:

经过几次尝试后,我现在得到了我想要的东西(即使代码可能不是 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/

【讨论】:

    【解决方案2】:

    像这样?: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;
        };
    });
    

    【讨论】:

    • 感谢 Gregg,这已经接近尾声了,但我需要的是仅包含 h1 文本的结果并作为链接,以便在单击它时导航到该章并恢复整个内容.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 2011-02-14
    • 2012-06-06
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多