我有一个网络应用程序,其中有多个带有 class="classA"
的元素。我想选择一个函数并将其应用于所有这些函数。我正在做一件显而易见的事情,那就是 $(".classA").each(function () { ... })
。这在 Chrome/Safari/Firefox 中工作得很好,但在 IE 中确实很慢。事实证明,在 jQuery 中通过 CSS 类选择内容时,IE 存在严重的性能问题。
我想知道是否有人有关于处理此问题的好方法的建议。我无法使用 ID 选择器,因为我想选择多个 DOM 元素。
-- 编辑--
下面是我的测试代码。
test1 使用
document.getElementById("id")
并且速度非常快。test2 使用
$("#id")
并且速度相当慢。test3 使用
$(".class")
并且速度更慢。
据我所知,IE8 中没有 document.getElementsByClassName 的 native 实现 - 当我尝试使用它时出现错误。
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript">
function test1 ()
{
var start = (new Date).getTime();
for (var i = 0; i < 10000; i++)
{
document.getElementById("test1");
}
var elapsed = (new Date).getTime() - start;
alert("test1 elapsed: " + elapsed);
}
function test2 ()
{
var start = (new Date).getTime();
for (var i = 0; i < 10000; i++)
{
var x = $("#test2");
}
var elapsed = (new Date).getTime() - start;
alert("test2 elapsed: " + elapsed);
}
function test3 ()
{
var start = (new Date).getTime();
for (var i = 0; i < 10000; i++)
{
$(".test3");
}
var elapsed = (new Date).getTime() - start;
alert("test3 elapsed: " + elapsed);
}
</script>
</head>
<body>
<div id="test1">test1</div>
<div id="test2">test2</div>
<div id="test3" class="test3">test3 1</div>
<div id="test3" class="test3">test3 2</div>
<div id="test3" class="test3">test3 3</div>
<div id="test3" class="test3">test3 4</div>
<input type="button" onclick="test1();" value="test1" />
<input type="button" onclick="test2();" value="test2" />
<input type="button" onclick="test3();" value="test3" />
</body>
</html>
最佳答案
看看jQuery: Performance analysis of selectors :
Test 2 - Finding an element by Class
Although CSS classes are intended to be reused among elements, you might create some elements with a unique class name just to identify and retrieve them through javascript. This is exactly what we test in this second test by seaching the element whose class is "p-4781". We have four alternatives:
A - Using the class selector
$('.p-4781').html()
B - Using the class selector + tag
$('p.p-4781').html()
C - Using attribute search + tag
$('p[class="p-4781"]').html()
D - Using tag search + filter
$('p').filter('.p-4781').html()
After running this test for the first time in different browsers, I got:
Firefox Opera IE6 IE7 Safari A 2891 641 1718 631 329 B 453 78 313 180 78 C 422 109 578 201 187 D 203 266 375 210 94
The table above shows case B as the fastest selector for most browsers (except Firefox). It is easy to understand why case A isn't efficient, since the code has to iterate over all elements of the DOM tree. Case C and D aren't that bad, but I would say case B should be the preferred one for this goal.
因此使用标签名称加类名称。在旧版浏览器中速度要快得多。
关于IE 中 CSS 类的 Jquery 选择器确实很慢 - 有解决方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3058208/