2016-07-06 3 views
2

나는 내 사이트에 포함 된 검색 스크립트에서 결과를 제한하지 않고 노력 해왔다.지킬 검색 결과 제한

 // Iterate over the results 
    for (var i = 0; i < results.length && i < 5; i++) { 
     var item = loaded_date[results[i]]; 

나는 ': 결과를 반복 할 때 나는이 제한 문을 포함하는 성공하지 않고 노력했습니다

jQuery(function() { 
 
    // Initialize lunr with the fields to be searched, plus the boost. 
 
    window.idx = lunr(function() { 
 
    this.field('id'); 
 
    this.field('title'); 
 
    this.field('content', { boost: 10 }); 
 
    this.field('categories'); 
 
    }); 
 

 
    // Get the generated search_data.json file so lunr.js can search it locally. 
 
    window.data = $.getJSON('/search.json'); 
 

 
    // Wait for the data to load and add it to lunr 
 
    window.data.then(function(loaded_data){ 
 
    $.each(loaded_data, function(index, value){ 
 
     window.idx.add(
 
     $.extend({ "id": index }, value) 
 
    ); 
 
    }); 
 
    }); 
 

 
    // Event when the form is submitted 
 
    $("#site_search").submit(function(event){ 
 
     event.preventDefault(); 
 
     var query = $("#search_box").val(); // Get the value for the text field 
 
     var results = window.idx.search(query); // Get lunr to perform a search 
 
     display_search_results(results); // Hand the results off to be displayed 
 
    }); 
 

 
    function display_search_results(results) { 
 
    var $search_results = $("#search_results"); 
 

 
    // Wait for data to load 
 
    window.data.then(function(loaded_data) { 
 

 
     // Are there any results? 
 
     if (results.length) { 
 
     $search_results.empty(); // Clear any old results 
 

 
     // Iterate over the results 
 
     results.forEach(function(result) { 
 
      var item = loaded_data[result.ref]; 
 

 
      // Build a snippet of HTML for this result 
 
      var appendString = '<li><a href="' + item.url + '">' + item.title + '</a></li>'; 
 

 
      // Add the snippet to the collection of results. 
 
      $search_results.append(appendString); 
 
     }); 
 
     } else { 
 
     // If there are no results, let the user know. 
 
     $search_results.html('<li><b><u>NO RESULTS FOUND</u></b></li>'); 
 
     } 
 
    }); 
 
    } 
 
});

그리고 다음은

는 원래 스크립트입니다 꽤 오랫동안 그것을 주변에 들여다 보았고, 어리 석다는 것을 발견 할 수 없었습니다.

모든 도움을 주시면 대단히 감사하겠습니다.

-d

답변

0

어떤 오류가 발생 했습니까? for 루프가 정상적으로 보입니다.

다른 방법으로 Array#slice을 사용하면 반복되는 결과의 수를 제한 할 수 있습니다.

results.slice(0, 5).forEach(function (result) { 
    // snip 
}) 

results.forEach이 결과, 이상 기존의 반복을 교체합니다.

결과가 5 개 미만인 경우에도 작동하며 결과가 5 개 이상이면 처음 5 개가됩니다.

+0

대단히 감사합니다, Caio. 위의 코드에서이 배열 # 슬라이스 스 니펫은 어디에 배치해야합니까? – drugstoreblonde

+0

또한 내가 얻은 오류는 검색이 실행될 때 결과가 전혀 표시되지 않고 단순히 404 페이지로 리디렉션된다는 것입니다. – drugstoreblonde

+0

슬라이스 호출을 어디에서 사용할지 설명하기 위해 필자의 대답을 업데이트했습니다. –