How to speed up jQuery for events on many elements
I'm using the following jQuery code to highlight the row the mouse is over:
$("#rpt tr:has(td):not(.noHighlight)").hover(
function() { $(this).css("background-color", "Silver"); 开发者_如何学编程},
function() { $(this).css("background-color", "Transparent"); }
);
When I start getting more than 500 rows, there is a noticeable delay, as the color is about 1/2 second behind the cursor. For very long tables, this causes IE to offer to stop the script as it takes a long time to render.
Is there a better/faster way to achieve this affect that can handle a large number of rows?
If you can add a .highlight class onto the rows you want to highlight you can just use css like this:
tr.highlight {
background-color: blue;
}
tr.highlight:hover
{
background-color : red;
}
500 rows on a page is a bit much for a user to digest a time. I suggest solving this by making use of pagination (only showing the list a little bit at a time)
If the color changing slowness is caused by jQuery searching for what to do, then this will help. Right now you are using jQuery("#") ID selector, that's awesome. On a large page/dom, you can go a step farther and you can tell limit jQuery's DOM searching explicitly like this:
jQuery("tr:has(td):not(.noHighlight)","#rpt").hover(
function() { $(this).css("background-color", "Silver"); },
function() { $(this).css("background-color", "Transparent"); }
);
Right now, you're searching the entire dom for "#rpt". the second parameter explicity tells jQuery to start searching the dom within the second parameter only.
精彩评论