【问题标题】:Jquery script freezing browser but workingJquery脚本冻结浏览器但工作
【发布时间】:2012-02-11 12:45:11
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery search live


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,刚刚试过,速度够快,现在自定义输出有问题,谢谢
    【解决方案2】:

    您可以将每个更改为:

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

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

    如果您需要更有创意的解决方案,请告诉我。

    【讨论】:

    • 你应该转义输入文本:filter.toUpperCase().replace('"', '\\"')
    【解决方案3】:

    首先,您可以将#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);
    

    【讨论】:

    • 我试过了,搜索速度确实更快,但对于 iphone 浏览器来说还不够快,但还是谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    相关资源
    最近更新 更多