Jquery脚本正在冻结浏览器,但正在工作

Jquery script freezing browser but working

本文关键字:工作 冻结 脚本 Jquery 浏览器      更新时间:2023-09-26

我正在尝试对我的移动网站进行实时搜索,我不想每次用户键入一封信都查询数据库,所以我创建了一个包含所有可以搜索的名称的有序列表,并用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);
        });

使用jQuery自动完成版本。您可以加载一个包含所有名称的数组,并将其传递给自动完成,这将在运行中起作用。

http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/

您可以将每个更改为:

var text = $("ol.pacientes li:contains('""+filter.toUpperCase()+"'")").map(function() {
    return $(this).text();
}).join(' ');
$('#pacientes_hint').text(text);

除了更短之外,唯一的改进是只在最后设置$('#pacientes_hint')的内容,这可能会有所帮助。

如果您需要更具创造性的解决方案,请告诉我。

首先,您可以将#pacientes_hint移动到每个函数之外。

$(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;
                } // end if

    }); // end each
     $('#pacientes_hint').html(html);

然后,您可以在keyup处理程序之前将ol.pacientes定义为一个变量,这样它就不会每次都查找它,在每个函数中,在变量内部搜索:

$(document).ready(function(){
var pacientes_list = $("ol.pacientes");
var pacientes_hint = $("#pacientes_hint");
$("input#search").keyup(function(){
    ...
    $("li", $(pacientes_list)).each(function(){ // search in the container
       ...     
    }); // end each
     $(pacientes_hint).html(html);