我一直在努力将结果限制在我网站中包含的搜索脚本中。
这是原始剧本:
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>');
}
});
}
});
我在尝试迭代结果时试图将此限制语句包括在内,但没有成功:
// Iterate over the results
for (var i = 0; i < results.length && i < 5; i++) {
var item = loaded_date[results[i]];
我已经玩了很长一段时间了,似乎无法找到什么是错误的。
非常感谢任何帮助。
-d
答案 0 :(得分:0)
你得到了什么错误,你的for循环看起来很好。
另一种方法是使用Array#slice来限制迭代结果的数量。
<?php
/
$action=$_POST['action'];
if ($action=="insert_marketer"){
insert_marketer();
}
function insert_marketer(){
$marketer=mysqli_connect("localhost","root","","marketer detail");
$username = $_POST['username'];
var_dump("$username");
$password = $_POST['password'];
$phone_number = $_POST['phone_number'];
if (!empty($username) && !empty($password)&& !empty($phone_number) ){
$password=crypt('$password');
$result = mysqli_query($marketer,"INSERT INTO 'marketer detail'('username','password','phone_number')VALUES('$username','$password','$phone_number')");
if($result)
{
var_dump('$password');
echo "New record created successfully";
}
else {
echo "Error: ". mysqli_error($marketer);
}
}
mysqli_close ($marketer) ;
}
?>
将您现有的迭代替换为结果,其中包含results.slice(0, 5).forEach(function (result) {
// snip
})
。
即使结果少于5个,这也会有效,如果结果超过5个,则会采用前5个。