这是一个有趣的难题,我有一个 javascript 数据可视化,它在 Safari/Chrome 中运行良好,甚至在 IE 中运行良好。但是 Firefox 真的很慢。我注意到似乎正在减慢速度的代码部分。
变量 stats 是 var stats = [{"team":"IND","player":"Andrew Luck","position":"QB","round":1,"choice": 1,"尺寸":66}, ... ];
这是完整的代码。问题区域在底部。有谁知道为什么 Firefox 在运行时会出现问题?
(function($){
$(document).ready(function() {
var paper = Raphael("graph",390, 1600);
var selectedteam;
for (var i = 0 ; i <= 252; i++) {
var s = stats[i].size*.3;
stats[i].circles = paper.circle(stats[i].round*50-20, stats[i].choice*20, s*.75)
.attr({
"fill": "RGB(" + (89*.3-s)*14 + ", " + s*8 + ", 100)",
"stroke": "RGB(255,255,255)"
})
stats[i].circles.player = stats[i].player;
stats[i].circles.team = stats[i].team;
stats[i].circles.position = stats[i].position;
stats[i].circles.mouseout(function() {
for (var lines in stats) {
stats[lines].circles.animate({"opacity": "1"}, 500);
}
});
stats[i].circles.mouseover(function() {
selectedteam = this.team;
$('#error').empty().html("<div><p>" + this.player + ", " + this.position + "</p><p>" + this.team + "</p></div>");
//****THIS FOR LOOP IS REALLY REALLY SLOW IN FIREFOX*****
for (var lines=0; lines <=252; lines++) {
stats[lines].circles.stop().animate({"opacity": ".1"}, 50);
if (selectedteam === stats[lines].team) {
stats[lines].circles.stop().animate({"opacity": "1"}, 50);
}
}
});
}
});
})(jQuery);
最佳答案
在处理数组索引时,您应该使用 every 而不是 for 循环javascript 的函数迭代数组,或者为了避免兼容性问题,在创建数组时用 jQuery 表达式评估( $() 或 jQuery() )包装它并使用 .each() jQuery 的迭代方法。
尝试执行 this test在您的 Firefox 中查看它是如何运行的。
已更新
找到更好的循环测试here .
关于Javascript FF 慢速 Chrome/Safari 快速,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10452580/