实时搜索和过滤JavaScript



我有一个只有搜索栏的页面;我希望从API获取内容,在输入[搜索]时对其进行过滤,然后在页面上显示匹配项。更像这个插件的作用:https://lscf.pixolette.com/photography/请问我怎样才能做到这一点?

目前,我有这个代码。请问我做错了什么?

const search = document.getElementById('search_box');
const searchResults = document.getElementById('search-results');
const searchMessage = document.getElementById('search-message');
let users;
// Get users
const getUsers = async () => {
const res = await fetch('baseUrl/wp-json/wp/v2/posts');
users = await res.json();
};
// FIlter states
const searchUsers = searchText => {
// Get matches to current text input
let matches = users.filter(user => {
const regex = new RegExp(`^${searchText}`, 'gi');
// return user.displayName.match(regex) || 
user.abbr.match(regex);
});
console.log(matches);
// Clear when input or matches are empty
if (searchText.length === 0) {
matches = [];
searchResults.innerHTML = '';
}
outputHtml(matches);

};

// Show results in HTML
const outputHtml = matches => {
if (matches.length > 0) {
const html = matches.map(match =>
`<div class="card card-body mb-1">
<h4>${match.title.rendered} (${match.id}) 
<span class="text-primary">${match.userPrincipalName}. 
</span></h4>
<small>ID: ${match.id} / Language: 
${match.preferredLanguage}</small>
</div>`
)
.join('');
searchResults.innerHTML = html;
}
};
window.addEventListener('DOMContentLoaded', getUsers);
search.addEventListener('input', () => searchUsers(search.value));

使用WordPress API 的示例

搜索框


<div>
<h4>Search blog by title</h4>
<div class="form-group ">
<input type="text" name="search_box" id="search_box" class="form-control" placeholder="Search by slug e.g my-title" onfocus="this.value=''" >
</div>
</div>

显示结果


<table id='results'>
</table>

搜索框AJAX


//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms (5 seconds)

//on keyup, start the countdown
$('#search_box').keyup(function(){
clearTimeout(typingTimer);
if ($('#search_box').val()) {  
var text = $('#search_box').val();    
typingTimer = setTimeout(doneTyping(text), doneTypingInterval)
}
});
//user is "finished typing," do something
function doneTyping (text) {
//do something
// var text = text;
var api_url_search = `/wordpress/wp-json/wp/v2/posts?slug=${text}`;
$.ajax({
url:api_url_search,
dataType: 'json',
success: function(response){
var len = response.length;                     
for(var i=0; i<len; i++){
var id = response[i].id;
var date = response[i].date_gmt;
var slug = response[i].slug;
var excerpt = response[i].excerpt.rendered;
var categories = response[i].categories;
var search_str =
'<td>'+
'<div class="card" style="width: 300px;">' +
'<div class="card-divider">' + (i+1) + ' ' + slug + '</div>' +    
' <div class="card-section">' +   
'<p>' + excerpt + '</p>' +
'<h4>' +  date + '</h4>' +
'<h4>' + 'Category:' + categories + '</h4>' +
'<a href="somepage.php?">'+ 
'<input type="button" value="read more">' + '</input>' +
' </a>' +
' </div>' +
'</div>'+
'</td>'           
;
$('#results').empty().append(search_str);
} 
}
});
};

相关内容

  • 没有找到相关文章

最新更新