jQuery代码导致内存泄漏 [英] jQuery code causing memory leak

查看:221
本文介绍了jQuery代码导致内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码导致内存泄漏(您将鼠标悬停在其中的次数越多,看到的越多).不幸的是,我无法在我的办公室中下载javascript分析器(我可以,这将花费我几天/几周的时间).

The following code is causing a memory leak (you can see this happening the more you hover in and out the slower it gets). Unfortunately I am unable to download a javascript profiler in my office (I can, it will just take me a few days/ weeks).

这是代码,只是下拉菜单的一些简单转换:

Here is the code, just some simple transitions for a dropdown menu:

$(document).ready(function(){
    breadcrumbOver = function () {
        $(this).stop().animate({ backgroundColor: "#3393b5", textIndent: 15 }, 250);
    }
    breadcrumbOut = function () {
        $(this).stop().animate({ backgroundColor: "#738793", textIndent: 0 }, 250);
    }
    $("nav ul li").hover(
      function () {
        $(this).children('ul.child').stop().slideDown('fast').children('li').hover(breadcrumbOver, breadcrumbOut);
      }, 
      function () {
        $(this).children('ul.child').stop().slideUp('fast').unbind(breadcrumbOver, breadcrumbOut);
      }
    );
});

谁能看到可能发生内存泄漏的地方?

Can anyone see where a memory leak may be occuring?

此处为实时示例- http://rcnhca.org.uk/sandbox/(反复滚动健康,安全和安保",然后将其滚动到孩子身上,以查看效果是否发生,并且如果滚动得足够快,动画slideDown有时也不会触发).

Live example here - http://rcnhca.org.uk/sandbox/ (Repeatedly roll over "Health, Safety and Security" then roll over it's children to see the effect happen, also the animation slideDown doesn't fire sometimes if you roll in and out fast enough).

推荐答案

问题似乎出在最初的选择器中.它以navul下的所有li标签为目标,其中包括所有子代和子代.

The problem looks like it might be in your initial selector. It targets all li tags under a ul under nav, which includes all children and grandchildren.

$("nav ul li") ...

这会导致它向nav下的所有li标签添加hover回调,然后当您将鼠标悬停时,它还会添加另一个hover回调.

This causes it to add a hover callback to all li tags under nav, then when you hover it adds yet another hover callback.

您可能希望对其进行更具体的说明,例如专门针对直接孩子.

You might want to be more specific with it, such as specifically targeting the direct children.

$("nav>ul>li")

如果有子类,则还可以使用:not(.child)定位所有非子类.使用console.log(Chrome内置或使用Firebug)记录这些选择器要提取的内容,以确保您获得了期望的结果.

If you have children classes, you can also use :not(.child) to target everything that's not a child. Use console.log (which is built into Chrome or using Firebug) to log what those selectors are pulling to make sure you're getting what you expect.

这篇关于jQuery代码导致内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆