[英]jQuery or DOM performance
On one of my web-pages, i need to have a list of words, each of which should get a border around it when clicked. 在我的一个网页上,我需要有一个单词列表,单击时每个单词都应有一个边框。 When another word is clicked, the previous one looses the border and the new one gets one. 单击另一个单词时,前一个单词将松开边框,而新单词将得到一个。 I will also need to show a div with some options for the clicked word. 我还需要显示一个div,其中包含一些用于单击单词的选项。
To achieve goal I used jQuery. 为了实现目标,我使用了jQuery。 The idea is simple: to remove a class with no border from the previous element and to add a class with a border to a new one. 这个想法很简单:从上一个元素中删除没有边框的类,并向新元素添加带有边框的类。 However, this works painfully slow when the number of such words gets into hundreds. 但是,当此类单词的数量达到数百时,这会非常缓慢。 How can i improve that? 我该如何改善呢? By the way, it renders slowly, too. 顺便说一下,它的渲染速度也很慢。
Here is the code i use (without the CSS) 这是我使用的代码(没有CSS)
HTML 的HTML
...
<div class="wrapper">
<div class='invis'>
<span word="24">YOu are a cool programmer</span>
</div>
</div>
...
JQuery Javascript: jQuery Javascript:
var currentElement = null;
$('.invis').click(function() {
if (currentElement != null) {
currentElement.removeClass("bordered");
currentElement.addClass("invis");
}
$(this).removeClass("invis");
$(this).addClass("bordered");
currentElement = $(this);
});
Try doing it the old fashion way without a library, something like: 尝试以不带库的老式方式进行操作,例如:
var invis = document.getElementsByClassName('invis'), last=false;
for (var i=0; i<invis.length; i++) {
invis[i].addEventListener("click", function(e) {
if (last) last.className = 'invis';
this.className = 'bordered';
last=this;
});
}
Turns out, the culprit was "float:left" for the .invis and .bordered in CSS. 原来,罪魁祸首是CSS中.invis和.bordered的“ float:left”。 Without that it started working significantly faster. 没有它,它的运行速度将大大加快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.