2012-09-18 55 views
0

我正在使用客户端VBScript将旧的经典ASP应用程序升级到使用jQuery的更现代的框架。在这种情况下,我的jQuery替换在IE8中运行速度明显慢于以前的VBScript。这里是我更换的脚本:通过选择元素选项加速jQuery搜索

Function Find() 
    name = Ucase(MyForm.SearchBox.value) 
    For x = 0 to MyForm.ComboBox.Length - 1 
    If Ucase(Left(MyForm.ComboBox.options(x).text,len(name)))=name Then 
     MyForm.ComboBox.options(x).Selected = True 
     Exit Function 
    End If 
    Next 
End Function 

这里是我的更换:

var text = $('#SearchBox').val(); 
$('#ComboBox option').each(function() { 
    if ($(this).text().toUpperCase().indexOf(text.toUpperCase()) == 0) { 
    $(this).prop('selected', true); 
    return false; 
    } 
}); 

有完全没有延迟/冻结运行的VBScript。用户可以按自己想要的速度输入,并且搜索功能保持不变。在同一台机器上,使用相同的数据,jQuery解决方案对文本响应延迟非常明显;看起来好像键盘输入在搜索过程中被冻结。

ComboBox元素是一个带有约3,500 option元素的HTML select。此方法正在搜索框的keyup事件中触发。

我可以做些什么优化让jQuery像旧VBScript一样快?

+0

建议之一是宣布'变量$此= $(本);'和使用'$ this'variable而不是使用'$(本)'多次,这将使jQuery的搜索每次对象。但我不确定在这种情况下它对你有多大帮助! – BlackCursor

回答

0

我最终在排序的选项上实现二分搜索。我猜jQuery引擎在IE8上对这种搜索类型的VBScript引擎效率不高。

var searchFoo = function(text) { 
    var searchFor = text.toUpperCase(); 
    var options = $('#ComboBox > option'); 

    var low = 0; 
    var mid; 
    var high = options.length - 1; 
    var target; 

    while (low <= high) { 
     mid = Math.ceil(low + (high - low)/2); 
     target = 
      options.eq(mid).text().toUpperCase().substring(0, searchFor.length); 

     if (searchFor < target) { 
      high = mid - 1; 
     } else if (searchFor > target) { 
      low = mid + 1; 
     } else { 
      // We found an option that matches. We want the *first* option that 
      // matches, so search up through the array while they still match. 
      while (mid > 0) { 
       target = 
        options.eq(mid - 1).text().toUpperCase() 
         .substring(0, searchFor.length); 
       if (searchFor == target) { 
        mid--; 
       } else { 
        return options.eq(mid); 
       } 
      } 
      return options.eq(mid); 
     } 
    } 

    return null; 
} 
0

在这里你去,以这条线应该加快速度:

var t = $('#SearchBox').val().toUpperCase(); 

$('#ComboBox > option[value="' + t + '"]').attr('selected', true); 

这里是我的jsfiddle检验出来时,我的代码来获得这个结果:

http://jsfiddle.net/YE3wG/

+0

在循环外部获取大写搜索值是一个很好的优化;谢谢!但是,除非我错过了一些东西,否则你的测试是不一样的。我在做一个不区分大小写的“开始于”与每个选项的文本进行比较。 –

+0

哦,当然,你100%正确 - 在我的解决方案中完全忘记了这一点。在那种情况下,我可以最优化你的代码是我的jsFiddle中注释掉的解决方案。 –

+0

此外,请记住选择器中将保存处理的“>”。而且,元素名称越短(不止一次使用)越快,它将用于3500元素循环,比如make var t = $(this).text(); etc. –

相关问题