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 sit amet urna quis dui rhoncus venenatis iaculis id arcu. Proin sit amet tincidunt est. Aenean ut tellus lectus. Vestibulum ac enim orci.

世界 « Interdum tempus » と書くと、結果が表示されます: « …laoreet interdum tempus. Aliquam 座って… »

出来ますか ?

助けてくれてどうもありがとう。

4

1 に答える 1

0

オートコンプリートと検索用語の強調表示を混同している可能性があります。あなたは__したいですか:

  1. ユーザーがより多くの文字を入力すると、可能なテキストの選択肢がゆっくりと表示されます (つまり、Google の提案) -または-
  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 に答える