Jquery 脚本冻结浏览器但可以工作
我正在尝试对我的移动网站进行实时搜索,我不想每次用户输入字母时都查询数据库,因此我创建了一个有序列表,其中包含可以搜索的所有名称,并且我正在循环通过它与 jquery,问题是我有 3300 个名称,并且当它搜索它们时它会冻结浏览器,任何人都可以给我一些关于更好的方法的提示吗?这是我的代码:
$(document).ready(function(){
$("input#search").keyup(function(){
var filter = $(this).val(), count = 0;
var html = "";
$("ol.pacientes li").each(function(){
var nome_paciente = $(this).text();
if(nome_paciente.indexOf(filter.toUpperCase()) != -1){
html = html + " " + nome_paciente;
}
$('#pacientes_hint').html(html);
});
i'm trying to make a live search for my mobile website, I don't want to query the database every time a user type a letter so I created a ordered list with all the names that can be searched for and i'm looping through it with jquery, problem is that I have 3300 names and it's freezing the browser when it searches through them, can anyone give me a tip about better ways to do it? here is my code:
$(document).ready(function(){
$("input#search").keyup(function(){
var filter = $(this).val(), count = 0;
var html = "";
$("ol.pacientes li").each(function(){
var nome_paciente = $(this).text();
if(nome_paciente.indexOf(filter.toUpperCase()) != -1){
html = html + " " + nome_paciente;
}
$('#pacientes_hint').html(html);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 jQuery 自动完成版本。您可以加载包含您所有姓名的数组并将其传递给自动完成功能,这将即时工作。
http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
Use the jQuery autocomplete version. You can load an array with all your names and pass it in to autocomplete, which will work on the fly.
http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
您可以将每个更改为:
除了更短之外,唯一的改进是仅在最后设置
$('#pacientes_hint')
的内容,这可能会有所帮助。如果您需要更具创意的解决方案,请告诉我。
You could change your each to:
Besides being shorter, the only improvement will be setting the contents of
$('#pacientes_hint')
only at the end, which could help.Let me know if you need a more creative solution.
首先,您可以将 #pacientes_hint 移到每个函数之外。
然后,您可以在 keyup 处理程序之前将 ol.pacientes 定义为变量,这样它就不会每次都查找它,并且在每个函数中,在变量内部搜索:
First of all, you could move #pacientes_hint outside the each function.
Then, you can define ol.pacientes as a variable before the keyup handler, so it doesn't look for it everytime and in the each function, search inside the variable: