2012-04-28 2 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의 ipsum의의 슬픔을, AMET consectetur의 adipiscing의 ELIT 앉아. Duis nibh urna. 알렉산드르의 아치 또는 벨소리. Ut volutpat hendrerit sollicitudin. 퀴 스케 (Quisque) 전표 축사 rhoncus. Curabitur laoreet interdum tempus. 알리미는로 표시됩니다. Proin은 tincidunt 동부 표준시에 앉는다. Aenean ut tellus lectus. Vestibulum ac enim orci.

싶습니다 당신이 세상을 작성하는 경우«Interdum 템퍼»결과 표시한다 : «... laoreet interdum 템퍼 스. Aliquam sit ...»

가능합니까?

많은 도움을 주셔서 감사합니다.

+0

... 난에 추가하여 질문을 편집 한 당신이 제출 한 새로운 정보를 조금 더 간결하게 .... 또한 PHP가 처리 된 후에 표시되는 HTML을 추가 할 수 있다면 솔루션을 함께 누락하는 것이 마지막 일 것입니다. – bcmoney

답변

0

자동 완성과 검색 단어 강조 표시가 혼동을 줄 수 있습니다. 천천히

  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 검색 파일 ("search"라고합니다.)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/

  • 관련 문제