我有一个这样的输入字段
<input type="text" placeholder="Search" id="search" />
,并希望在用户仍在键入时阅读内容,然后在搜索字符串匹配时显示数据。我想我需要一个异步函数,但是我不知道如何继续处理字符串。
async function readSearchString(){
return document.getElementById("search").value;
}
function processString(cell, string)
{
// Keep doing this
var searchString = await readSearchString();
if (cell.includes(searchString))
{
cell.visibility = "hidden";
}
}
我是否需要以无限循环的方式运行整个函数,以保持用户输入的效果?
答案 0 :(得分:2)
您可以根据需要使用onchange
,onkeyup
,onkeydown
等输入事件。
function processString()
{
var searchString = document.getElementById("search").value;
console.log('Search key :'+ searchString);
// You can do your search code here
/*
if (cell.includes(searchString))
{
cell.visibility = "hidden";
}
*/
}
<input type="text" placeholder="Search" id="search" onkeyup="processString()">
答案 1 :(得分:0)
我认为您想要这样的东西。我曾经做过的事
var searchRequest = null; //prevent multiple unnecessary requests to the server.
$(function () {
var minlength = 3;
$("#sample_search").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
if (searchRequest != null)
searchRequest.abort();
searchRequest = $.ajax({
type: "GET",
url: "sample.php",
data: {
'search_keyword' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
//Receiving the result of search here
}
}
});
}
});
});