使用XML突出显示自动完成功能

时间:2012-04-28 10:47:19

标签: jquery-ui jquery-ui-autocomplete

我正在使用基于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坐下来,精神上的精神。 DUIS   诋毁nibh urna。在arcu vel diam malesuada malesuada的Aliquam。 UT   volutpat hendrerit sollicitudin。 Quisque vestibulum adipiscing   rhoncus。 Curabitur laoreet interdum tempus。 Aliquam坐下来   du rhoncus venenatis iaculis id arcu。 Proin坐在amet tincidunt est。   Aenean ut tellus lectus。 Vestibulum ac enim orci。

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

有可能吗?

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

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

  1. 当用户输入更多字母时,慢慢显示可能的文字选择(即Google建议) -OR -
  2. 在搜索结果页面中突出显示已搜索的字词
  3. 或者您可能想要同时执行这两项操作,但看起来您正在谈论示例代码中的突出显示,尽管您的问题是关于自动完成...

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

    <?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.")";
    
    ?>
    

    DEMO: http://bcmoney-mobiletv.com/widgets/autocomplete/