2012-04-28 10 views
0

XMLファイルに基づいてオートコンプリートで検索を作成しています。 ユーザーが単語を入力すると、テキストがhightlighになります。私がこれまで行ってきた何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のイプサムの悲しみは、AMET consecteturのadipiscingのELIT座ります。 Duis nibh urnaを嫌う。 Aliquam in arcu vel diam malesuada malesuada。 Ut volutpat hendrerit sollicitudin。クスケ前庭アディピシング rhoncus。 Curabitur laoreet interdum tempus。アリクラムは、アールヌーキーの の座にあります。 Proinはtincidunt est。 Aenean ut tellus lectusに座っています。 Vestibulum ac enim orci。

私はあなたが世界を記述する場合は«Interdumテンパス»、結果表示希望: «... laoreet interdumテンパスを。 Aliquam sit ...»

それは可能ですか?

ご協力いただきありがとうございます。

+0

...私は中に追加することによって、あなたの質問を編集しましたPHPの処理後に表示されるHTMLを追加することができれば、解決策を得るために最後に欠落してしまうことになります。 – bcmoney

答えて

0

オートコンプリートと検索語の強調表示が混乱することがあります。あなたがしたいですか:ユーザー種類以上の文字(つまり、Googleの提案) - または -

  • ハイライトが既に検索結果ページに用語のため
  • を検索するよう

    1. ゆっくり可能テキストの選択肢を明らかにする

      または両方を実行したい場合は、サンプルコードからのハイライトについて話しているようですが、オートコンプリートに関する質問はありますが...

      とにかくここには説明と検索のオートコンプリートのコードがあります用語の強調表示:

      <?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> 
      

      PHP検索ファイル(「検索」と呼ばれます)。PHP」)を使用したxPath:ここ

      <?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/

    関連する問題