简体   繁体   中英

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.

To achieve goal I used 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)

HTML


...

<div class="wrapper">
    <div class='invis'>
        <span word="24">YOu are a cool programmer</span>
    </div>
</div>

...

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;
    });
}

FIDDLE

Turns out, the culprit was "float:left" for the .invis and .bordered in CSS. Without that it started working significantly faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM