开发者

I Have a question about jquery performance

Will I have a performance problem if there are 500 elements with this class?

$('.class开发者_Go百科').hover(function handleIn() { /*code*/ },function handleOut() { /*code*/ });


If there are a lot of nodes with the classname class (you mentioned 500) jquery will bind 500 distinct event handler methods for each node. That of course is slower in comparison to only one event handler which handles all nodes.

That is the principle of event delegation and event bubbling. If there is a parent node which all of these .class nodes share, you can delegate any event to that parent node. Of course all elements share the document.body, so for demonstration it is:

$(document.body).delegate('.class', 'mouseenter', function(e) {
    // code when entering
}).delegate('.class', 'mouseleave', function(e) {
   // code when leaving
});

As mentioned, document.body can/should get replaced with a shared parent node which is closer to the nodes. You can also distinct between the hovered nodes in those delegated event handlers by checking the event object or this, both reference the current node if invocation.


You should declare the functions once outside the hover event. So they are created only once and not 500 times:

 function handleIn(){}
 function handleOut(){} 

$('.class').hover(handleIn,handleOut);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜