0

我正在创建一个基于 XML 文件的自动完成搜索。我想当用户输入一个单词时,文本会很突出。

到目前为止我做了什么:

$(function() {

    function log( message ) {
        $( "<div/>" ).text( message ).prependTo( "#log" );
        $( "#log" ).scrollTop( 0 );
    }

    $.ajax({
        url: "ecole.xml",
        dataType: "xml",
        success: function( xmlResponse ) {
            var data = $( "school", xmlResponse ).map(function() {

                return {
                    value: $( "name", this ).text() + ", " +
                        ( $.trim( $( "adress", this ).text() ) + ", " + $( "description", this ).text() || "(unknown article)" ),
                    id: $( "id", this ).text(),
                    text: $( "description", this ).text()
                };
            }).get();

            $( "#birds" ).autocomplete({
                    source: data,
                    minLength: 0,
                    select: function( event, ui ) {
                        log( ui.item ?
                            "Selected: " + ui.item.value + ", Id: " + ui.item.id + ", Text: " + ui.item.text :
                            "Nothing selected, input was " + this.value ); 
                    },
            });
        }
    });
});

我真的不明白如何突出显示文本。我使用这段代码:

$(function() {
    highlight: function(match, keywords) {
       keywords = keywords.split(' ').join('|');
       return match.replace(new RegExp("("+keywords+")", "gi"),'<b>$1</b>');
    }
});

但我现在真的不知道为什么而且它不起作用

这是我的 HTML / PHP :

    <div id="RecentEdition">
    <?php
    $schools = simplexml_load_file('ecoles.xml');
    foreach ($schools->RecentEdition as $RecentEdition): 
      foreach ($RecentEdition->school as $school):  ?>
        <figure>
          <img src='<?php echo "{$school->image} \n"; ?>' title='' />
          <figcaption>
            <h3>Contents</h3>
            <p class="over">
              <ul>
                  <?php foreach ($school->content as $content):  ?>
                    <?php foreach ($content->chap as $chap):  ?>
                      <li><a href="<?php echo "{$chap['link']} \n"; ?>"><?php echo "{$chap} \n"; ?></a></li>
                    <?php endforeach; ?>
                  <?php endforeach; ?>
              </ul>
            </p>
            <p class="go">
              <a href="<?php echo "{$school->link} \n"; ?>">View »</a>
            </p>
          </figcaption>
        </figure>
      <?php endforeach; ?>
    <?php endforeach; ?>
  </div>

这是我的 XML:

    <?xml version="1.0" encoding="utf-8"?>
    <schools>    
    <RecentEdition>
        <school>
            <name>École1</name>
            <id>1</id>
            <link>./Marlburian0809/index.html</link>
            <image>./img/zine.jpg</image>
            <content>
                <chap link="./Marlburian0708/#/2/">The Master's Speech</chap>
                <chap link="./Marlburian0809/#/8/">College Community</chap>
                <chap link="./Marlburian0809/#/50/">Trips n Expeditions</chap>
                <chap link="./Marlburian0809/#/64/">Creative Arts</chap>
                <chap link="./Marlburian0809/#/92/">Sports</chap>
            </content>
            <description>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer luctus porta turpis, id congue nisi dapibus nec. Maecenas pulvinar blandit turpis, sit amet viverra arcu convallis id. Donec varius blandit orci nec molestie. Cras auctor, metus eget volutpat hendrerit, massa nibh tempor nunc, volutpat ultrices nibh eros vestibulum nulla. Aenean libero risus, auctor sed blandit ut, tincidunt non est. Nullam bibendum nunc non tortor eleifend consectetur. Proin porttitor, diam ac varius semper, leo odio mattis erat, id luctus ligula libero eu mi. Proin et lacus ligula. Quisque non consequat mauris. Morbi dolor mi, dapibus a condimentum ac, luctus at elit. Praesent sit amet felis at magna sagittis pharetra et vitae neque. 
            </description>
        </school>
    </RecentEdition>
  </schools>

还有一个问题。如果我的自动完成中有一个大文本,例如:

Lorem ipsum dolor sit amet, consectetur adipiscing elit。Duis vulputate nibh urna。Aliquam in arcu vel diam malesuada malesuada。Ut volutpat hendrerit sollicitudin。Quisque 前庭 adipiscing rhoncus。Curabitur laoreet interdum tempus。Aliquam 坐在 amet urna quis dui rhoncus venenatis iaculis id arcu。Proin sit amet tincidunt est. Aenean ut Tellus lectus。前庭 ac enim orci。

我希望如果你写世界« Interdum tempus »,结果显示:« ...laoreet interdum tempus。Aliquam 坐... »

可能吗 ?

非常感谢您的帮助。

4

1 回答 1

0

您可能会混淆自动完成和搜索词突出显示。你想要_____吗:

  1. 随着用户输入更多字母(即谷歌建议),慢慢显示可能的文本选择 - 或 -
  2. 在搜索结果页面中突出显示已搜索的术语

或者也许你想两者都做,但看起来你正在谈论示例代码中的突出显示,尽管你的问题是关于自动完成......

无论如何,这里有一些自动完成描述和搜索词突出显示的代码:

<?php

$q = filter_var($_REQUEST['q'], FILTER_SANITIZE_STRING);
$query = (isset($q) && !empty($q)) ? $q : "";

?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Autocomplete/SearchHighlighting Example</title>
        <link type="text/css" href="css/ui-lightness/jquery-ui-1.8.20.custom.css" rel="stylesheet" />
    <style type="text/css">
    span.highlighted {
        background-color: #FFF6C6;
        font-weight: bold;
    }
    span.term0 {
        color: #161633;
    }
    span.term1 {
        color: #331616;
    }
    span.term2 {
        color: #163316;
    }
    </style>
        <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
        <script type="text/javascript" src="js/jquery-ui-1.8.20.custom.min.js"></script>
  <!--[if lt IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->
  <style type="text/css">
    header, section, footer, aside, nav, article, figure, figcaption, audio, video, canvas  { display:block; }
  </style>
</head>
<body>
    <form id="search" name="search">
      <label for="q">Search: </label><input type="text" id="q" name="q" value="<?php echo $query; ?>" placeholder="Enter a search term" />
    </form>
    <div id="RecentEdition">
    <?php
    $schools = simplexml_load_file('ecoles.xml');
    foreach ($schools->RecentEdition as $RecentEdition): 
      foreach ($RecentEdition->school as $school):  ?>
        <figure>
          <img src='<?php echo "{$school->image} \n"; ?>' title='' />
          <figcaption>
            <h3>Contents</h3>
            <p class="over">
              <ul id="results">
                  <?php foreach ($school->content as $content):  ?>
                    <?php foreach ($content->chap as $chap):  ?>
                      <li><a href="<?php echo "{$chap['link']} \n"; ?>"><?php echo "{$chap} \n"; ?></a></li>
                    <?php endforeach; ?>
                  <?php endforeach; ?>
              </ul>
            </p>
            <p class="desc"><?php echo "{$school->description} \n"; ?></p>
            <p class="go">            
              <a href="<?php echo "{$school->link} \n"; ?>">View &#187;</a>
            </p>
          </figcaption>
        </figure>
      <?php endforeach; ?>
    <?php endforeach; ?>
  </div>
  <script type="text/javascript">
    $(function() {
      //Autocomplete    
                $("#q").autocomplete({                  
                    //define callback to format results
                    source: function(req, add){                 
                        //pass request to server
                        $.getJSON('search.php?callback=?', req, function(data) {
                            var suggestions = []; //create array for response objects
                            //process response
                            $.each(data, function(i, terms){
                                suggestions.push(terms.term);
                            });
                            add(suggestions); //pass array to callback
                        });
                    },
          //define select handler:     Search Term Highlighting function
          select: function(match, keywords) {
            var rawSearchString = $('#q').val().replace(/[a-zA-Z0-9\?\&\=\%\#]+s\=(\w+)(\&.*)?/,"$1"); // Return sanitized search string if it exists (term should be FIRST URL PARAMETER)             
            var searchString =  rawSearchString.replace(/ /g,"\|").replace("?term=",""); //  Replace '+' and '%20' with '|' for regex 
            var searchTerms = searchString.split('|'); // Split search terms on '|' and iterate over resulting array                                       
            for (var j in searchTerms) {          
              var regex = new RegExp(">([^<]*)?("+searchTerms[j]+")([^>]*)?<", "ig"); // this regex is the secret, it prevents text within tag declarations from being affected              
              var tempHTML = $('#RecentEdition').html(); // Do regex replace
              $('#RecentEdition').html(tempHTML.replace(regex, '>$1<span class="highlighted term'+j+'">$2</span>$3<')); // Inject span with class of 'highlighted termX' for term highlighting                             
            }
          }
                });    
    });
  </script>
</body>
</html>

以及使用 xPath 的 PHP 搜索文件(称为“search.php”):

<?php

header('content-type: application/json; charset=utf-8');

$term = urldecode($_REQUEST['term']);
$callback = $_GET["callback"];

$html = new DOMDocument();
@$html->load("ecoles.xml");
$xpath = new DOMXPath($html);
$query = "//schools/RecentEdition/school/description[contains(.,'".$term."')]";
$nodelist = $xpath->query($query);

$i = 0;
foreach ($nodelist as $n) {
  $result = trim($n->nodeValue);
  $resultArray[$i] = array( "term" => str_replace('"',"'",substr($result,strpos($result,$term),25)) );
  $i++;
}

$resultJSON = json_encode($resultArray);
echo $callback."(".$resultJSON.")";

?>

演示在这里: http ://bcmoney-mobiletv.com/widgets/autocomplete/

于 2012-05-01T16:07:35.370 回答