Joh*_*ohn 6 javascript jquery jquery-selectors
我在StackOverflow上找到了一个不区分大小写的jQuery 选择器的解决方案:contains.它运行良好,但它以性能为代价.有没有其他人觉得这个解决方案有点慢?
我正在使用:contains选择器来搜索表格.用户在文本框中键入搜索字符串.对于每次击键,它会在表中搜索该字符串,仅显示通过:contains选择器包含该字符串的行.在实施不区分大小写的解决方案之前,此搜索快速而且快速.现在有了这个解决方案,它会在每次击键后锁定一小段时间.
关于如何加快这个解决方案的任何想法?
Joh*_*ohn 10
我在Google上找到了另一种不区分大小写搜索的解决方案(参见Eric Phan),这与我最初使用的解决方案略有不同.
原版的:
return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
Run Code Online (Sandbox Code Playgroud)
EricPhan:
return (a.textContent || a.innerText || "").toLowerCase().indexOf(m[3].toLowerCase())>=0;
Run Code Online (Sandbox Code Playgroud)
比较两者,你可以看到Eric Phan的解决方案直接访问DOM属性toLowerCase()而不是使用toUpperCase().后者并不重要,但前者真正改善了不区分大小写搜索的性能.只需更改原始解决方案即可使用(a.textContent || a.innerText || "")而不是jQuery(a).text()完全不同!
现在我有点好奇,所以这是一个跟进问题:有什么处理jQuery.text()?为什么这么慢?我有我的假设,但我很想听听专家们的意见.
最后,感谢所有回复的人.我恭维你的帮助.=)
在用户停止键入指定的时间后,您可以尝试仅检查选择器一次,而不是每次按键.
例如,一个简单的实现:
用法:
$("#textboxId").keyup(function () {
typewatch(function () {
// executed only 500 ms after the user stopped typing.
}, 500);
Run Code Online (Sandbox Code Playgroud)
执行:
var typewatch = function(){
var timer = 0; // store the timer id
return function(callback, ms){
clearTimeout (timer); // if the function is called before the timeout
timer = setTimeout(callback, ms); // clear the timer and start it over
}
}();
Run Code Online (Sandbox Code Playgroud)